Find the length of the longest substring without repeating characters.
This problem follows the Variable Window + Set pattern, commonly found in the Sliding Window category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Expand window right. When duplicate found, shrink from left until no duplicate.
The window only expands or slides right — each character is added and removed from the set at most once, giving O(n) despite the inner while loop.
charSet = set()
left = 0
maxLen = 0
for right in range(len(s)):
while s[right] in charSet:
charSet.remove(s[left])
left += 1
charSet.add(s[right])
maxLen = max(maxLen, right - left + 1)
return maxLenPractice Longest Substring Without Repeating Characters and similar Sliding Window problems with flashcards. Build pattern recognition through active recall.
Practice this problem