Problem 9 · Two Pointers & Sliding Window
Longest Substring Without Repeating Characters
01Problem
Return the length of the longest substring of s with no repeated characters.
02Key insight
Variable-size sliding window with a last-seen index map: on a repeat, jump the left edge past the previous occurrence instead of shrinking one step at a time.
03Solution
Try it first.
TimeO(n)
SpaceO(min(n, alphabet))
tests.py · 4 passing
tests.pypython4 lines
assert length_of_longest_substring("abcabcbb") == 3
assert length_of_longest_substring("bbbbb") == 1
assert length_of_longest_substring("") == 0
assert length_of_longest_substring("abba") == 204Staff-level follow-up
Allow at most k distinct characters instead? Keep a count map and shrink from the left while len(map) > k; same O(n) window.