Longest Substring Without Repeating Characters

Medium

Topics
StringSliding WindowHash Table

Given a string s, find the length of the longest substring without repeating characters.

Example 1

a0b1c2a3b4c5b6b7length 3
The braced run is the longest stretch with no repeated character, length 3 (abc). The window only ever moves forwards: on a repeat, the left edge jumps past the previous occurrence rather than restarting, so each character is visited once.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "abcabcbb"
Output: 3
Explanation: The answer is "abc".

Example 2

b0b1b2b3b4length 1
Input:  s = "bbbbb"
Output: 1

Constraints

  • 0 <= s.length <= 5*10^4
  • s consists of English letters, digits, symbols and spaces.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Slide a window over the string keeping it free of duplicates. When the new character was already inside the window, jump the left edge to just past its previous position — that removes the duplicate in O(1).

The window only ever grows on the right and jumps forward on the left, so each character is handled once.

Approach

  1. Store the last index seen for each character and a left boundary.
  2. For character at right: if it was seen at index ≥ left, set left = lastSeen + 1.
  3. Record its new index and update the best length right - left + 1.

Walkthrough

s = "abcabcbb"
window grows to "abc" (len 3)
at index 3 (a): a seen at 0 -> left=1, window "bca"
... best stays 3 -> answer 3

Complexity

  • Time — O(n): each character is visited once; left only moves forward.
  • Space — O(min(n, charset)): at most one map entry per distinct character.

Common Pitfalls

  • The seen[c] >= left check matters — an old occurrence outside the window must be ignored.

Full Solution — all languages

class Solution:
    def lengthOfLongestSubstring(self, s):
        last = {}
        start = res = 0
        for i, c in enumerate(s):
            if c in last and last[c] >= start:
                start = last[c] + 1
            last[c] = i
            res = max(res, i - start + 1)
        return res
SensAI
Beta
Tap the mic to stop voice mode