Longest Substring Without Repeating Characters
Difficulty: Medium · Pattern: Sliding Window · LeetCode #3
Return the length of the longest substring (contiguous) of s in which no character appears more than once.
Examples
text
s = "abcabcbbx" → 3 ("abc")
s = "pwwkew" → 3 ("wke")
s = "dvdf" → 3 ("vdf")
s = "" → 0Hints
- Grow a window to the right. When the new character already appears inside the window, the left edge must move past its previous occurrence.
- Store each character's most recent index so the left edge can jump directly.
Approach
Maintain l (window start) and a map last[c] = most recent index of c. For each r:
- if
s[r]was seen at an index ≥l, it's inside the window, so setl = last[s[r]] + 1; - update
last[s[r]] = rand the best lengthr − l + 1.
The check ≥ l matters: an old occurrence before the window must not move l backwards (e.g., "abba").
Complexity
Time: O(n). Space: O(min(n, alphabet)).
Python solution
def lengthOfLongestSubstring(s):
last = {}
l = best = 0
for r, c in enumerate(s):
if c in last and last[c] >= l:
l = last[c] + 1
last[c] = r
best = max(best, r - l + 1)
return bestJavaScript solution
function lengthOfLongestSubstring(s) {
const last = new Map();
let l = 0, best = 0;
for (let r = 0; r < s.length; r++) {
const c = s[r];
if (last.has(c) && last.get(c) >= l) l = last.get(c) + 1;
last.set(c, r);
best = Math.max(best, r - l + 1);
}
return best;
}