Data Structures & Algorithms · Module 12 · Lesson 21 min read

Sliding Window

The idea

For problems about contiguous subarrays or substrings, keep a "window" [left, right] and update its state as it moves, instead of recalculating from scratch.

Fixed-size window

"Max sum of k consecutive items": add the item entering, subtract the item leaving.

Python
window = sum(a[:k])
for i in range(k, len(a)):
    window += a[i] - a[i - k]

Variable-size window

"Longest substring without repeating characters", "smallest subarray with sum ≥ target":

  1. Expand right one step at a time and add the new item to the window state.
  2. While the window breaks the rule, shrink from left.
  3. Record the best answer.

Each index enters and leaves the window at most once, so it's O(n).

Window state is usually…

  • a running sum,
  • a Counter or dict of character counts,
  • a set of items in the window,
  • a deque, for the max or min (Unit 5).

Recognise it

Keywords: "subarray", "substring", "consecutive", "contiguous", "longest or shortest… such that…".

PatternWindow
max or average of k itemsfixed
longest with at most K distinctvariable
minimum window containing all of Tvariable + counts
anagram of P in Sfixed (size of P) + counts

Example

Python
from collections import Counter

def max_sum_k(nums, k):
    window = best = sum(nums[:k])
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

def longest_unique(s):
    last, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

def min_subarray_len(target, nums):
    left, total, best = 0, 0, float("inf")
    for right, x in enumerate(nums):
        total += x
        while total >= target:
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else best

def find_anagrams(s, p):
    need, window, out = Counter(p), Counter(s[:len(p)]), []
    if window == need: out.append(0)
    for i in range(len(p), len(s)):
        window[s[i]] += 1
        window[s[i - len(p)]] -= 1
        if window == need: out.append(i - len(p) + 1)
    return out

print(max_sum_k([2, 1, 5, 1, 3, 2], 3))        # 9
print(longest_unique("abcabcbb"))              # 3
print(min_subarray_len(7, [2, 3, 1, 2, 4, 3])) # 2
print(find_anagrams("cbaebabacd", "abc"))      # [0, 6]