Skip to content
prdlk
Esc
↑↓navigate↵open⌘Jpreview
On this page

Sliding Window

Sliding window is a specialized two-pointer family where the pointers define a contiguous interval and you maintain information about that entire interval as it moves.

Many problems have two moving boundaries. That alone does not make them sliding window problems.

A problem belongs to this family when:

  • the answer depends on the subarray or substring between left and right
  • you can update the window state incrementally as elements enter or leave
  • you maintain a condition that tells you whether the window is valid
What is an invariant?

An invariant is a statement that stays true before and after every iteration. In a sliding window, that statement usually describes the window itself, such as “the window is valid,” “it has no duplicates,” or “its sum is at most the target.” It can also describe a helper structure, such as “the frequency map matches the characters currently inside the window.”

Why invariants matter?

Without an invariant, shrinking the window is just a guess. You no longer know when the window is valid, when to update the answer, or why the left pointer should stop. The invariant is what makes the algorithm correct.

How sliding window differs from other two-pointer families?

Sliding window is not the same as every other two-pointer pattern. In Container With Most Water, the interval is only the remaining search space. In sliding window, the interval itself is the thing you care about. In Remove Duplicates, the left side is already the finished answer prefix. In sliding window, both pointers describe a live window that is still being checked.

1. Fixed-size windows

Sliding Window Fixed
def sliding_window_fixed(input, window_size):
    ans = window = input[0:window_size]
    for right in range(window_size, len(input)):
        left = right - window_size
        remove input[left] from window
        append input[right] to window
        ans = optimal(ans, window)
    return ans

Add nums[right] to the window.

If the window has k elements, record the answer.

Remove the leftmost element so the window stays at size k.

2. Flexible-size windows with a validity rule

Sliding Window Flexible
def sliding_window_flexible_longest(input):
    initialize window, ans
    left = 0
    for right in range(len(input)):
        append input[right] to window
        while invalid(window):        # update left until window is valid again
            remove input[left] from window
            left += 1
        ans = max(ans, window)        # window is guaranteed to be valid here
    return ans
def sliding_window_flexible_shortest(input):
    initialize window, ans
    left = 0
    for right in range(len(input)):
        append input[right] to window
        while valid(window):
            ans = min(ans, window)      # window is guaranteed to be valid here
            remove input[left] from window
            left += 1
    return ans

Add nums[right] to the window.

While the window is invalid, remove nums[left] and move left up.

The window is now valid. Record its size.


3. Frequency-tracking windows

Frequency-tracking windows
from collections import defaultdict

def frequency_window(s):
    left = 0
    counts = defaultdict(int)
    best = 0

    for right in range(len(s)):
        counts[s[right]] += 1                # character enters

        while counts[s[right]] > 1:          # rule: no repeats
            counts[s[left]] -= 1             # character leaves
            left += 1

        best = max(best, right - left + 1)

    return best

Add s[right] to the window.

While the window has more than one character, remove s[left] and move left up.

The window is now valid. Record its size.


For anagram or “minimum window substring” problems, you also keep a target count. Track how many characters currently match the target with one integer (matched). Update it only when a count crosses the target value. This keeps each step O(1).

def anagram_window(s, p):
    need = defaultdict(int)
    for c in p:
        need[c] += 1

    counts = defaultdict(int)
    matched = 0                  # how many chars have counts[c] == need[c]
    result = []
    k = len(p)

    for right in range(len(s)):
        c = s[right]
        counts[c] += 1
        if counts[c] == need[c]:
            matched += 1

        if right >= k:                       # window too big, remove left
            d = s[right - k]
            if counts[d] == need[d]:
                matched -= 1
            counts[d] -= 1

        if matched == len(need):
            result.append(right - k + 1)

    return result

Last updated on

Was this page helpful?