All Topics

Sliding Window & Two Pointers

Fixed and variable-width windows for substring, subarray, and two-pointer problems

0/34 solved

Fixed Window

Process subarrays of exact size K using a sliding window

O(n) O(1)

Approach

Build initial window of size K. Slide right: add new element, remove leftmost. At each position, compute the required metric (sum, max, min, average). This gives O(n) instead of O(n*K).

How to Recognize

1

Problem specifies a fixed window size K

2

Need max/min/sum of all subarrays of size K

3

Phrases like 'subarray of size K', 'K consecutive elements'

4

Window size doesn't change as it slides

Pro Tips

Initialize window with first K elements, then slide by adding right and removing left

Use a deque for max/min in window in O(1) amortized

Don't forget edge case: array length < K

8

Total

5

Easy

2

Medium

1

Hard

Time

O(n)

Space

O(1)