← Back to Algorithms, page 2

algorithms-0022 · Medium fresher

Longest substring without repeating characters: find the length of the longest substring in which no character repeats.

Grow a window with a right pointer and remember the last index of each character. When the new character was already seen inside the window, jump the left pointer to just after that earlier position. The window always contains unique characters, each pointer only moves forward, and the scan is O(n).

Full answer

Problem

Given a string s, return the length of the longest substring with all distinct characters.

Example: "abcabcbb" gives 3 ("abc"); "pwwkew" gives 3 ("wke"; "pwke" is a subsequence, not a substring).

Constraints: 0 <= len(s) <= 5 x 10^4; letters, digits, symbols and spaces.

Brute force

Check every substring for uniqueness with a set: O(n^3), or O(n^2) if you extend each start until a repeat appears.

Optimal approach

Keep left (window start) and a dictionary last_seen from character to its latest index. For each right:

  1. If s[right] is in last_seen and that index is at least left, set left = last_seen[s[right]] + 1.
  2. Store last_seen[s[right]] = right.
  3. Update best = max(best, right - left + 1).

Why it works

Invariant: s[left:right + 1] has no repeats. When a repeat appears, any window that still contains the earlier copy is invalid, so the left edge must move past it; moving further would only shrink the window for no reason. The check last_seen[ch] >= left matters: in "abba", when the second a arrives, the earlier a at index 0 is already outside the window [2, 3], and jumping back would be wrong.

Complexity

O(n) time. O(min(n, alphabet size)) space for the dictionary.

Code

python
def length_of_longest_substring(s):
    """Longest substring without repeating characters. Variable sliding window, O(n)."""
    last_seen = {}                 # char -> last index
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1          # jump past the earlier copy
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best


def brute(s):
    return max((j - i for i in range(len(s)) for j in range(i, len(s) + 1)
                if len(set(s[i:j])) == j - i), default=0)


if __name__ == "__main__":
    for f in (length_of_longest_substring, brute):
        assert f("abcabcbb") == 3
        assert f("bbbbb") == 1
        assert f("pwwkew") == 3
        assert f("") == 0
        assert f(" ") == 1
        assert f("abba") == 2
        assert f("dvdf") == 3
    print("all tests passed")

Save as a22_longest_unique_substring.py and run python3 a22_longest_unique_substring.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty string returns 0. A single space returns 1. All identical characters returns 1. "abba" and "dvdf" test the "earlier copy outside the window" condition.

Pattern

Variable-size sliding window: expand on the right, shrink (or jump) on the left to restore the condition. The general template uses a while loop to shrink; here the last-seen index lets the left edge jump in one step.

python
def length_of_longest_substring(s):
    """Longest substring without repeating characters. Variable sliding window, O(n)."""
    last_seen = {}                 # char -> last index
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1          # jump past the earlier copy
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best


def brute(s):
    return max((j - i for i in range(len(s)) for j in range(i, len(s) + 1)
                if len(set(s[i:j])) == j - i), default=0)


if __name__ == "__main__":
    for f in (length_of_longest_substring, brute):
        assert f("abcabcbb") == 3
        assert f("bbbbb") == 1
        assert f("pwwkew") == 3
        assert f("") == 0
        assert f(" ") == 1
        assert f("abba") == 2
        assert f("dvdf") == 3
    print("all tests passed")

Left edge jumps using a last-seen dictionary; a brute-force reference is tested on the same inputs.

Complexity

Time: O(n). Space: O(min(n, alphabet size)). Each pointer moves forward only, so the total work is linear.

By level

Fresher: Explains the window idea with a set and a shrinking loop, tracing "abcabcbb". Should state that both pointers only move forward.

Mid: Uses the last-seen jump, handles the stale-index case and generalises to at most k distinct characters. Explains why the check against the left edge matters for "abba".

Senior: Discusses alphabet size effects on memory, Unicode handling and a general template for variable windows with different validity conditions. Can explain how the method changes when the input is a stream of characters.

Key points

  • Window holds unique characters only
  • Store the last index of each character
  • Jump left past the earlier copy, only if it is inside the window
  • Both pointers move forward only
  • Substring is contiguous; subsequence is not

Common mistakes

  • Moving left backwards when the earlier copy is outside the window
  • Resetting the whole window on a repeat
  • Confusing substring with subsequence
  • Using a set and forgetting to remove characters as the window shrinks

Follow-ups

  • What if at most k distinct characters are allowed?
  • How would you return the substring itself?
  • What changes for Unicode text?

Tips

  • State the window invariant
  • Test "abba"
  • Explain why the algorithm is linear

Evaluation rubric

  • Correct O(n) algorithm
  • Handles the stale index case
  • Correct complexity
  • Clear invariant