Sliding Window Patterns
4 patterns and 19 practice problems, each with a recall tip, a diagram, the theory and a Python template.
Sliding Window - Fixed Size (Subarray Calculation)
5 practice problems
How to recall this pattern
Visual diagram
Theory
- The window size k is given. Initialize by computing the result for the first k elements.
- Slide one step at a time: add nums[i], remove nums[i - k]. Update the answer each step.
- Works for rolling sums, rolling averages, max sum of size-k subarray, and count-based checks.
- Time: O(n), Space: O(1) — each element is visited exactly once.
Code template
def max_sum_subarray(nums, k):
window_sum = sum(nums[:k])
max_sum = window_sum
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k]
max_sum = max(max_sum, window_sum)
return max_sumPractice problems · 5
Compute the sum of the first k elements. Slide the window: add the new right element, subtract the element leaving on the left. Track the max sum and divide by k at the end for the average.
def findMaxAverage(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best / kBase satisfaction = sum when not grumpy. Then slide a window of size "minutes" to find the window that recovers the most grumpy-lost customers. Add the best extra to base.
def maxSatisfied(customers, grumpy, minutes):
base = sum(c for c, g in zip(customers, grumpy) if g == 0)
extra = sum(customers[i] for i in range(minutes) if grumpy[i])
best = extra
for i in range(minutes, len(customers)):
if grumpy[i]: extra += customers[i]
if grumpy[i - minutes]: extra -= customers[i - minutes]
best = max(best, extra)
return base + bestInstead of dividing by k every step, compare the window sum directly against k * threshold. Slide the fixed window and count how many positions meet the condition.
def numOfSubarrays(arr, k, threshold):
target = k * threshold
window = sum(arr[:k])
count = 1 if window >= target else 0
for i in range(k, len(arr)):
window += arr[i] - arr[i - k]
if window >= target:
count += 1
return countMaintain a set of at most k elements (the current window). If the new element is already in the set, we found a duplicate within distance k. Otherwise add it and evict the oldest if the set exceeds size k.
def containsNearbyDuplicate(nums, k):
window = set()
for i, n in enumerate(nums):
if n in window:
return True
window.add(n)
if len(window) > k:
window.remove(nums[i - k])
return FalseCount vowels in the first k characters. Slide the window: add 1 if the new char is a vowel, subtract 1 if the leaving char was a vowel. Track the max count.
def maxVowels(s, k):
vowels = set('aeiou')
count = sum(1 for c in s[:k] if c in vowels)
best = count
for i in range(k, len(s)):
count += (s[i] in vowels) - (s[i - k] in vowels)
best = max(best, count)
return bestSliding Window - Variable Size (Condition-Based)
5 practice problems
How to recall this pattern
Visual diagram
Theory
- Expand the window by advancing the right pointer and updating window state.
- When the constraint is violated, shrink from the left until valid again.
- For "longest" problems: update the answer before or while the window is valid. For "shortest": update after shrinking to a valid state.
- Each element enters and leaves the window at most once — O(n) total even with the inner while loop.
Code template
def longest_subarray(nums, k):
left = 0
total = 0
result = 0
for right in range(len(nums)):
total += nums[right]
while total > k:
total -= nums[left]
left += 1
result = max(result, right - left + 1)
return resultPractice problems · 5
Use a dict to track the last index of each character. When a repeat is found within the current window, jump left past the previous occurrence. This keeps the window always free of duplicates.
def lengthOfLongestSubstring(s):
seen = {}
left = 0
best = 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1
seen[ch] = right
best = max(best, right - left + 1)
return bestExpand right to grow the sum. Once sum >= target, record the window length, then shrink left to find the shortest valid window. The while loop ensures we try all valid shrinks before expanding again.
def minSubArrayLen(target, nums):
left = 0
total = 0
best = float('inf')
for right in range(len(nums)):
total += nums[right]
while total >= target:
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return best if best != float('inf') else 0The key insight: window_size - max_freq_in_window = number of characters to replace. If that exceeds k, shrink from left. max_freq never needs to decrease — we only care about finding a larger window.
def characterReplacement(s, k):
counts = {}
left = 0
max_freq = 0
best = 0
for right in range(len(s)):
counts[s[right]] = counts.get(s[right], 0) + 1
max_freq = max(max_freq, counts[s[right]])
while (right - left + 1) - max_freq > k:
counts[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return bestThis is "longest subarray with at most 2 distinct elements." Use a frequency map as the basket. When more than 2 types exist, shrink from left, removing fruits from the map when their count hits 0.
def totalFruit(fruits):
basket = {}
left = 0
best = 0
for right, f in enumerate(fruits):
basket[f] = basket.get(f, 0) + 1
while len(basket) > 2:
basket[fruits[left]] -= 1
if basket[fruits[left]] == 0:
del basket[fruits[left]]
left += 1
best = max(best, right - left + 1)
return bestCount zeros in the window. When zeros exceed k (the number of flips allowed), shrink from the left. The answer is the longest window that contains at most k zeros.
def longestOnes(nums, k):
left = 0
zeros = 0
best = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > k:
if nums[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left + 1)
return bestSliding Window - Monotonic Queue for Max/Min
4 practice problems
How to recall this pattern
Visual diagram
Theory
- A monotonic deque keeps candidate indices in sorted order of their values, so the front is always the current max (or min).
- When adding a new element, pop from the back while the new element is >= (for max-deque) or <= (for min-deque) the back element.
- Before using the front, check if its index is still within the window — if not, pop it from the front.
- This gives O(1) amortized max/min queries per step, O(n) total time.
Code template
from collections import deque
def sliding_window_max(nums, k):
dq = deque() # stores indices, decreasing order of values
result = []
for i in range(len(nums)):
# remove indices outside the window
while dq and dq[0] < i - k + 1:
dq.popleft()
# maintain decreasing order
while dq and nums[dq[-1]] <= nums[i]:
dq.pop()
dq.append(i)
if i >= k - 1:
result.append(nums[dq[0]])
return resultPractice problems · 4
Monotonic decreasing deque of indices. Before adding index i: (1) pop front if outside window, (2) pop from back while value <= nums[i]. The front always holds the index of the current window max.
from collections import deque
def maxSlidingWindow(nums, k):
dq = deque() # indices in decreasing value order
result = []
for i, n in enumerate(nums):
while dq and dq[0] < i - k + 1:
dq.popleft()
while dq and nums[dq[-1]] <= n:
dq.pop()
dq.append(i)
if i >= k - 1:
result.append(nums[dq[0]])
return resultBuild prefix sums. Use a monotonic increasing deque on prefix values. For each i, pop from front while prefix[i] - prefix[front] >= k (valid subarray found, record length). Pop from back while prefix[back] >= prefix[i] (they can never be better starting points).
from collections import deque
def shortestSubarray(nums, k):
n = len(nums)
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + nums[i]
dq = deque() # monotonic increasing on prefix values
best = float('inf')
for i in range(n + 1):
while dq and prefix[i] - prefix[dq[0]] >= k:
best = min(best, i - dq.popleft())
while dq and prefix[dq[-1]] >= prefix[i]:
dq.pop()
dq.append(i)
return best if best != float('inf') else -1DP where dp[i] = nums[i] + max(dp[i-k..i-1]). Use a monotonic decreasing deque to get the max of the last k dp values in O(1). Pop front if out of range, use front as the max, then maintain deque order when inserting.
from collections import deque
def maxResult(nums, k):
n = len(nums)
dp = [0] * n
dp[0] = nums[0]
dq = deque([0]) # max deque on dp values
for i in range(1, n):
while dq and dq[0] < i - k:
dq.popleft()
dp[i] = dp[dq[0]] + nums[i]
while dq and dp[dq[-1]] <= dp[i]:
dq.pop()
dq.append(i)
return dp[-1]Two deques: one for max (decreasing), one for min (increasing). If max - min > limit, shrink from left and pop deque fronts that fell out of window. The answer is the longest window where the difference stays within limit.
from collections import deque
def longestSubarray(nums, limit):
max_dq = deque() # decreasing
min_dq = deque() # increasing
left = 0
best = 0
for right, n in enumerate(nums):
while max_dq and nums[max_dq[-1]] <= n:
max_dq.pop()
while min_dq and nums[min_dq[-1]] >= n:
min_dq.pop()
max_dq.append(right)
min_dq.append(right)
while nums[max_dq[0]] - nums[min_dq[0]] > limit:
left += 1
if max_dq[0] < left: max_dq.popleft()
if min_dq[0] < left: min_dq.popleft()
best = max(best, right - left + 1)
return bestSliding Window - Character Frequency Matching
5 practice problems
How to recall this pattern
Visual diagram
Theory
- Build a frequency map of the target/pattern. Maintain a frequency map of the current window.
- Use a "matched" or "formed" counter: increment when a character reaches its required count, decrement when it drops below.
- When matched == required, the window contains a valid match. Record it and try shrinking.
- For fixed-length pattern matching (anagrams), the window size equals the pattern length. For minimum window substring, the window is variable.
Code template
from collections import Counter
def find_anagrams(s, p):
need = Counter(p)
window = {}
required = len(need)
matched = 0
result = []
for i in range(len(s)):
ch = s[i]
window[ch] = window.get(ch, 0) + 1
if ch in need and window[ch] == need[ch]:
matched += 1
# remove left element when window exceeds pattern length
if i >= len(p):
left_ch = s[i - len(p)]
if left_ch in need and window[left_ch] == need[left_ch]:
matched -= 1
window[left_ch] -= 1
if matched == required:
result.append(i - len(p) + 1)
return resultPractice problems · 5
Initialize a Counter for both the pattern and the first window. Slide one character at a time: add the new right char, remove the leftmost char. When the two Counters are equal, record the start index. Comparing Counters is O(26) for lowercase letters.
from collections import Counter
def findAnagrams(s, p):
if len(p) > len(s): return []
need = Counter(p)
window = Counter(s[:len(p)])
result = []
if window == need: result.append(0)
for i in range(len(p), len(s)):
window[s[i]] += 1
left = s[i - len(p)]
window[left] -= 1
if window[left] == 0: del window[left]
if window == need: result.append(i - len(p) + 1)
return resultSame approach as Find All Anagrams but return True as soon as a single match is found. Fixed window of size len(s1) slides across s2 comparing frequency counts.
from collections import Counter
def checkInclusion(s1, s2):
n1, n2 = len(s1), len(s2)
if n1 > n2: return False
need = Counter(s1)
window = Counter(s2[:n1])
if window == need: return True
for i in range(n1, n2):
window[s2[i]] += 1
left = s2[i - n1]
window[left] -= 1
if window[left] == 0: del window[left]
if window == need: return True
return FalseVariable window with frequency matching. Expand right, incrementing "formed" when a char reaches its needed count. When formed == required, try shrinking from left to minimize. Record the shortest valid window.
from collections import Counter
def minWindow(s, t):
need = Counter(t)
window = {}
required = len(need)
formed = 0
left = 0
best = (float('inf'), 0, 0)
for right in range(len(s)):
ch = s[right]
window[ch] = window.get(ch, 0) + 1
if ch in need and window[ch] == need[ch]:
formed += 1
while formed == required:
if right - left + 1 < best[0]:
best = (right - left + 1, left, right)
window[s[left]] -= 1
if s[left] in need and window[s[left]] < need[s[left]]:
formed -= 1
left += 1
return '' if best[0] == float('inf') else s[best[1]:best[2]+1]Maintain a frequency map of window characters. When distinct count exceeds k, shrink from left, deleting entries that reach 0. The longest valid window is the answer.
def lengthOfLongestSubstringKDistinct(s, k):
freq = {}
left = 0
best = 0
for right, ch in enumerate(s):
freq[ch] = freq.get(ch, 0) + 1
while len(freq) > k:
freq[s[left]] -= 1
if freq[s[left]] == 0:
del freq[s[left]]
left += 1
best = max(best, right - left + 1)
return bestExactly k distinct = atMost(k) - atMost(k-1). The atMost helper counts subarrays with at most k distinct using a variable sliding window. For each right, the number of valid subarrays ending there is (right - left + 1).
def subarraysWithKDistinct(nums, k):
def atMost(k):
freq = {}
left = 0
count = 0
for right, n in enumerate(nums):
freq[n] = freq.get(n, 0) + 1
while len(freq) > k:
freq[nums[left]] -= 1
if freq[nums[left]] == 0:
del freq[nums[left]]
left += 1
count += right - left + 1
return count
return atMost(k) - atMost(k - 1)Spotted a mistake on this page?
Wrong formula, broken animation or confusing wording. Tell us and we will fix it.