Problem Statement
Longest Substring Without Repeating Characters
You are given a string s. A substring is a run of characters that sit next to each other, with no gaps. Your job is to find the longest run where no character repeats, and return its length.
Signals to notice
Brute force first
Check every substring for unique characters — or. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Sliding window with a set: expand right, shrink left when duplicate found. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on s="pwwkew"
right=0 'p': not in set → add; set={p}, left=0, maxLen=1
right=1 'w': not in set → add; set={p,w}, left=0, maxLen=2
right=2 'w': dup → remove 'p'(left→1), remove 'w'(left→2); add 'w'; set={w}, maxLen=2
right=3 'k': not in set → add; set={w,k}, left=2, maxLen=2
right=4 'e': not in set → add; set={w,k,e}, left=2, window="wke", maxLen=3
right=5 'w': dup → remove 'w'(left→3); add 'w'; set={k,e,w}, maxLen=3
loop ends → return maxLen = 3What must stay true
The window always contains unique characters — shrink left until the duplicate is removed. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
set ← {}; left ← 0; maxLen ← 0
for right in 0..n-1:
while s[right] in set: # shrink from left
set.remove(s[left]); left ← left + 1
set.add(s[right])
maxLen ← max(maxLen, right - left + 1)
return maxLenPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Not shrinking the window properly — remove characters from the set as you move left. The fix is usually to return to the meaning of each move, not just the steps themselves.