Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•7 MIN

Sliding Window: Two Pointers That Only Move Forward

Longest substring without repeating characters, explained by the one reason it is O(n) and not O(n²).

sliding windowtwo pointershash mapstringshash mapamortized

The problem

Given a string, find the length of the longest substring with no repeated characters. "abcabcbb" gives 3 ("abc").

The brute force checks every substring, which is O(n²) or worse. The window version never looks at a character more than twice.

Watch it run

Pick pwwkew or dvdf, which trip up people who just reset the window on a duplicate. Watch how left moves only as far as it must.

LOADING SLIDING WINDOW SIM...

Why it is O(n)

It looks like a loop inside a loop, but the inner while is not independent. left only ever moves forward and never past right. Across the whole run:

  • right moves at most n times.
  • left moves at most n times.

That is at most 2n pointer moves in total. This kind of argument is called amortized analysis, and saying that word with the reason behind it is a strong signal in an interview.

The code

def length_of_longest_substring(s: str) -> int:
    seen: dict[str, int] = {}
    left = best = 0
    for right, ch in enumerate(s):
        seen[ch] = seen.get(ch, 0) + 1
        while seen[ch] > 1:          # window is invalid: shrink from the left
            seen[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

Recognizing the pattern

Reach for a sliding window when you see:

  1. A contiguous subarray or substring.
  2. A property you can maintain incrementally (a count, a sum, a set of distinct items).
  3. A request for the longest, shortest, or count of windows satisfying a constraint.
VariantWindow rule
Longest unique substringShrink while any character count is above 1
Minimum window substringGrow until valid, then shrink while still valid
Max sum of size-k subarrayFixed size: add the new element, drop the oldest
At most K distinctShrink while distinct count is above K