Longest Substring Without Repeating Characters

Find the length of the longest substring without repeating characters.

Pattern

Variable Window + Set

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.

Approach

How to Solve It

Expand window right. When duplicate found, shrink from left until no duplicate.

Key Insight

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.

Step-by-step

  1. 1Use a set to track characters in the current window
  2. 2Expand the window by moving the right pointer
  3. 3If a duplicate is found, shrink from the left until it's removed
  4. 4Update the max length at each step

Pseudocode

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 maxLen
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(min(n, m))
More Sliding Window Problems

Master this pattern with YeetCode

Practice Longest Substring Without Repeating Characters and similar Sliding Window problems with flashcards. Build pattern recognition through active recall.

Practice this problem