Difficulty: Medium | Asked at: Amazon, Meta, Bloomberg
Input: "abcabcbb"
Output: 3 ("abc")
Input: "bbbbb"
Output: 1 ("b")
💡 Hint: This screams sliding window. Keep expanding a window to the right, and when you hit a repeat, shrink from the left until the repeat is gone.
Solution:
python
def length_of_longest_substring(s):
seen = {}
left = 0
max_len = 0
for right, char in enumerate(s):
if char in seen and seen[char] >= left:
left = seen[char] + 1
seen[char] = right
max_len = max(max_len, right - left + 1)
return max_len
Complexity: O(n) time - each character is visited by
right once, and left only ever moves forward. O(min(n, alphabet size)) space for the hash map.Common mistake: Resetting
left to seen[char] + 1 even when the previous occurrence of char is OUTSIDE the current window (i.e., seen[char] < left). Without the seen[char] >= left check, you can accidentally move left backwards, which breaks the algorithm.Sliding window is one of the highest-ROI patterns to master - it solves a huge chunk of "substring" and "subarray" problems. Comfortable with it, or still building intuition? 👇