Longest Substring Without Repeating Characters
LeetCode 3 • Medium • Sliding Window
Find the length of the longest substring without repeating characters.
Input: s = "abcabcbb" → Output: 3 (substring "abc")
TimeO(n)each char at most 2x
SpaceO(min(n,128))char set
Ready
Press Play. Expand right, add char to set. If duplicate, shrink from left until unique. Track max length.
TimeO(n)same as iterative
SpaceO(n)call stack + set
Recursive: helper(right, left, char_set, result) — base when right ≥ n; else add s[right], shrink while duplicate, recurse right+1.
Practice until you don't need to look. The green highlights are the nuances to burn into memory.
PATTERN ▸ Sliding window + set (shrink when duplicate) O(n) · O(min(n,128))
① INIT
left=0, char_set=set(), result=0
② EXPAND RIGHT
for right in range(len(s)):
③ SHRINK WHILE DUPLICATE
while s[right] in char_set:
char_set.remove(s[left]); left += 1
④ ADD & UPDATE
char_set.add(s[right])
result = max(result, right - left + 1)
⑤ RETURN
return result
▼ your implementation ▼