PracticeNeetCode ↗LeetCode ↗
Given a string s, find the length of the longest substring that doesn't contain any repeated characters.
left = 0, a hashmap last_seen, and max_len = 0.right, character ch: if ch was seen at or after left, move left to just past that occurrence.ch's current index in last_seen.max_len with the current window size, right - left + 1.max_len.Time: O(n) — Space: O(min(n, charset size))
def lengthOfLongestSubstring(s: str) -> int:
last_seen = {}
left = 0
max_len = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1
last_seen[ch] = right
max_len = max(max_len, right - left + 1)
return max_lenHow the solution above works, piece by piece.
last_seen maps each character to the last index where it appeared.right grows the window one character at a time.ch was seen inside the current window (last_seen[ch] >= left), jump left just past that earlier copy. The >= left check ignores stale entries from before the window.ch's new position and update max_len with the window length right - left + 1.left only moves forward, and jumps instead of stepping: O(n) time, O(alphabet) space.Running it on s = "abcabcbb":
left jumps past its old position. The longest window without repeats has length 3 (abc).NeetCode — Longest Substring Without Repeating Characters, LeetCode 3