Longest Substring Without Repeating Characters

MediumSliding Window · Dynamic Size🧩 Sliding WindowLeetCode #3 ↗Updated

Problem

Given a string s, return the length of the longest contiguous piece of it in which no character appears twice. A subsequence (skipping characters) does not count — the characters must be adjacent.
Inputs = "abcabcbb"Output3 ("abc")
Inputs = "bbbbb"Output1 ("b")
Inputs = "pwwkew"Output3 ("wke")

0 ≤ n ≤ 5·104  ·  s holds English letters, digits, symbols and spaces (ASCII)

Try it yourself

Java
class Solution {
    public int lengthOfLongestSubstring(String s) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Keep a window [left..right] with no duplicates. When s[right] was already seen inside the window, jump left just past its previous index — every start before that would contain the same repeat.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceCheck Every Substring

Time O(n3)Space O(min(n, k))

Try every pair (i, j) and test whether s[i..j] is duplicate-free with a fresh HashSet. Keep the longest length that passes. (k = alphabet size.)

Java
public int lengthOfLongestSubstring(String s) {
    int n = s.length(), maxLength = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            if (isUnique(s, i, j)) maxLength = Math.max(maxLength, j - i + 1);
        }
    }
    return maxLength;
}

private boolean isUnique(String s, int start, int end) {
    Set<Character> chars = new HashSet<>();
    for (int k = start; k <= end; k++) {
        if (!chars.add(s.charAt(k))) return false; // already present
    }
    return true;
}

Obviously correct, but re-scans each of the O(n2) substrings from scratch.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every SubstringO(n3)O(min(n, k))
BetterSliding Window + HashSetO(n)O(min(n, k))
OptimalSliding Window + Last-Index TableO(n)O(k)
Common pitfalls
  • Setting left = last[c] without max — left moves backwards ("abba").
  • Off-by-one in window length: it is right - left + 1 for an inclusive window.
  • Using int[26] — input may contain digits, spaces and symbols.
Interview tips
  • Clarify the charset first; it decides array vs HashMap.
  • Explain why the set version is still O(n): each index enters and leaves once.
  • State the invariant: the window never contains a repeat.
Pattern
Variable-size sliding window → longest/shortest contiguous range satisfying a constraint that breaks monotonically.
My notes saved in this browser