Problem
Given a string
s, find the length of the longest substring without duplicate characters. A substring is a contiguous sequence of characters within a string.
Example 1
Input: s = "zxyzxyz"
Output: 3
The string "xyz" is the longest without duplicate characters.
Example 2
Input: s = "xxxx"
Output: 1
Constraints
0 <= len(s) <= 50,000smay consist of printable ASCII characters.
Thinking
- Brute force idea: for every start
i, extend to the right with a hash set until a character repeats, and keep the longest run. , where is the alphabet size (a run can’t be longer than ), so when the alphabet is unbounded. - Key insight: when the brute force restarts at
i + 1, it re-checks characters it already knows are distinct. Instead keep a window[l, r]that is always duplicate-free:radvances one step at a time, and whens[r]is already in the window, movelright (removings[l]from the set) until it isn’t. Each character enters and leaves the window at most once → . - Faster shrink: remember the last index of every character. On a repeat,
lcan jump straight tolast[c] + 1, with no inner loop. Guard it withmax(l, ...): an old index that is already left oflmust not move the window backwards. - Edge cases to remember: empty string (→ 0); all the same character (
"xxxx"→ 1); all distinct (→len(s)); the repeat is not at the window’s left end ("dvdf"→ 3: keep"v", drop only the first"d"); the duplicate is the character just beforer("abccd"→ 3); a character last seen beforel("abba"→ 2: the oldamust not pulllback); spaces and punctuation count as characters.
Solution
Approach A — mine: sliding window + hash set
Complexity: Time · Space
Already optimal in Big-O. Each iteration does the same three steps: shrink (remove s[l] and advance l while s[r] is still in the window), add s[r], update the best length. The inner while doesn’t make it : every character is added once and removed at most once, so the total work is . Polish only: starting max_l at 0 makes the if not s guard unnecessary.
def length_of_longest_substring_mine(s: str) -> int:
if not s: # unnecessary if max_l starts at 0
return 0
l, max_l = 0, 1
s_set = set()
for r in range(len(s)):
while s[r] in s_set: # shrink until s[r] can join; amortised O(1) per character
s_set.remove(s[l])
l += 1
s_set.add(s[r])
max_l = max(max_l, r - l + 1)
return max_l
Approach B — brute force: extend from every start
Complexity: Time · Space
For each start, grow a run until the first repeat. Obviously correct, so the tests use it as the reference on random strings. With only ~95 printable characters each run is short, so it’s less hopeless than , but it still re-scans the same characters over and over.
def length_of_longest_substring_brute(s: str) -> int:
best = 0
for i in range(len(s)):
seen = set()
for c in s[i:]: # restarts from scratch for every i
if c in seen:
break
seen.add(c)
best = max(best, len(seen))
return best
Approach C — sliding window + last-index map ✅ best practice
Complexity: Time · Space
The version to remember. Same window as A, but the dict stores where each character was last seen, so on a repeat l jumps straight past it instead of walking there one step at a time. Characters are never removed from the dict; the >= l check ignores entries that are already outside the window (that’s the "abba" trap).
def length_of_longest_substring(s: str) -> int:
last = {} # char -> index where it was last seen
l = best = 0
for r, c in enumerate(s):
if last.get(c, -1) >= l: # repeat inside the window: jump past it
l = last[c] + 1
last[c] = r
best = max(best, r - l + 1)
return best
Scratch / Experiments
Worst case for the brute force: the 95 printable characters repeated in a cycle up to the max length , so every start scans a full run of 95 before hitting a repeat. A random string is also timed, where runs are short and the brute force looks much better than it is.
Measured (): on the cyclic string, last-index map ~4.6 ms, mine ~5.9 ms, brute force ~183 ms (~30× slower). On the random string, map ~3.9 ms, mine ~7.0 ms, brute force ~55 ms.
Both windows are , but the map version is consistently faster: it does one dict lookup and one store per character, while the set version also does a remove + l += 1 for every character that leaves the window (up to set operations in total). The brute force is only ~10–30× slower rather than thousands of times, because caps every run; with an unbounded alphabet it would be truly .
chars = string.printable[:95]
cyclic = (chars * (50_000 // len(chars) + 1))[:50_000]
rng = random.Random(0)
random_s = "".join(rng.choice(chars) for _ in range(50_000))
for s in (cyclic, random_s):
assert length_of_longest_substring_mine(s) == length_of_longest_substring(s) == length_of_longest_substring_brute(s)
%timeit length_of_longest_substring_mine(s)
%timeit length_of_longest_substring(s)
%timeit -n 1 -r 3 length_of_longest_substring_brute(s)
Takeaways
- Pattern: “longest contiguous run where a condition holds” → sliding window.
ralways advances; when addings[r]would break the condition, shrink from the left until it holds again; then recordr - l + 1. Every element enters and leaves once, so the nestedwhileis still . If you can compute wherelmust go (here: one past the last copy ofs[r]), jump there directly with a last-index map. - Mistakes I made (in earlier drafts, before the final version):
- Changing
rinsidefor r in range(...)(r + 1,r = l + 1,r += 1): theforoverwrites it on the next iteration, so it does nothing or only works by accident. Compute lengths fromrandlinstead. - Never removing characters from the set when
lmoved, so characters outside the window still counted as duplicates. The set must hold exactly the window. - Removing
s[r]instead ofs[l]: the character that leaves whenlmoves is the one on the left. - Moving
lby one step (or jumping tor) instead of until the duplicate is gone → use awhile. - Splitting the loop into
if/elseand forgetting to adds[r]and update the answer in theelse. The fix was one shape for every iteration: shrink → add → update. - Tests that only cover the examples pass by luck:
"dvdf","abccd"and"abba"are the cases that actually exercise the shrink.
- Changing
- Related problems: Best Time to Buy and Sell Stock (#121, the simpler window where
ljumps on a new low); Longest Repeating Character Replacement (#424, window valid whilelen - max_count <= k); Permutation in String (#567) and Find All Anagrams (#438, fixed-size window with counts); Minimum Window Substring (#76, the “shortest” version: grow until valid, then shrink); Longest Substring with At Most K Distinct Characters (#340, same shape with a count map).