FAANGPrep Sprint
Longest Substring Without Repeating Characters
Find the length of the longest substring without repeating characters.
Examples
"abc" is the longest stretch with no repeated character, so the answer is 3.
Every character is "b", so no stretch longer than 1 avoids a repeat.
"wke" is the longest repeat-free stretch, length 3. "pwke" does not count: its letters are not contiguous in the input, so it is a subsequence rather than a substring.
Problem Understanding
We need to find the length of the longest substring in a given string s that contains no duplicate characters.
A substring is a contiguous sequence of characters. For example, in "abcabcbb", "abc" is a substring, but "acb" is not (it skips characters).
Algorithm Strategy
We use the Sliding Window technique with a Hash Map (or Array for fixed charsets) to track characters in the current window.
- Initialize
left = 0andmax_len = 0. - Use a
mapto store the most recent index of each character. - Iterate
rightfrom 0 to end of string:- If
s[right]is inmapand its index is>= left, it means we found a repeat inside our current window. Movelefttomap[s[right]] + 1to skip the previous occurrence. - Update
map[s[right]]to the currentrightindex. - Update
max_len = max(max_len, right - left + 1).
- If
- Return
max_len.
Key Insight: Instead of shrinking the window one character at a time, we can jump the left pointer directly past the duplicate. Both versions are O(N); the jump just skips the inner shrinking loop.
Interactive Visualization
"dvdf"
EMPTY WINDOW
0
1
2
3
left
0
right
—
Length
—
Best
0
map (char:last index)
Empty
left starts at 0, the map is empty and the best length is 0
Next
Read 'd' at 0
String
Watch how the window expands and jumps the left pointer when a duplicate is found.
