Sliding Window Technique: Solve Array and String Problems in O(n)
Learn the sliding window technique with fixed and variable windows: maximum sum subarray of size k, longest substring without repeating characters, minimum window substring and templates in Python and Java.
The sliding window technique solves problems about contiguous subarrays or substrings. Instead of recomputing each window from scratch, you keep a running result and update it as the window slides: add the element entering on the right, remove the one leaving on the left. That simple idea turns many O(n²) or O(n·k) solutions into O(n).
When to use it#
Look for these clues in the problem statement:
- The input is an array or string.
- You need a contiguous subarray or substring (not a subsequence).
- You're asked for the longest, shortest, maximum, minimum or count of windows meeting a condition.
Fixed-size windows#
Problem: find the maximum sum of any subarray of size k.
Brute force: O(n·k)#
def max_sum_brute(nums, k):
best = float("-inf")
for i in range(len(nums) - k + 1):
best = max(best, sum(nums[i:i + k])) # re-adds k numbers every time
return bestSliding window: O(n)#
def max_sum_window(nums, k):
window = sum(nums[:k])
best = window
for right in range(k, len(nums)):
window += nums[right] - nums[right - k] # add new, remove old
best = max(best, window)
return best
print(max_sum_window([2, 1, 5, 1, 3, 2], 3)) # 9 (5 + 1 + 3)Each element is added once and removed once, so the work is linear no matter how big k is.
Fixed window with a frequency map: find all anagrams#
from collections import Counter
def find_anagrams(s: str, p: str) -> list[int]:
k, need = len(p), Counter(p)
window = Counter(s[:k])
result = [0] if window == need else []
for right in range(k, len(s)):
window[s[right]] += 1
left_char = s[right - k]
window[left_char] -= 1
if window[left_char] == 0:
del window[left_char]
if window == need:
result.append(right - k + 1)
return result
print(find_anagrams("cbaebabacd", "abc")) # [0, 6]Variable-size windows#
Here the window grows and shrinks. The pattern uses two pointers:
- Move
rightforward to expand the window, adding the new element. - While the window is invalid, move
leftforward to shrink it. - Once valid, update the answer.
Longest substring without repeating characters#
def length_of_longest_substring(s: str) -> int:
last_seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump past the duplicate
last_seen[ch] = right
best = max(best, right - left + 1)
return best
print(length_of_longest_substring("abcabcbb")) # 3 ("abc")
print(length_of_longest_substring("pwwkew")) # 3 ("wke")public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastSeen = new HashMap<>();
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (lastSeen.containsKey(c) && lastSeen.get(c) >= left) {
left = lastSeen.get(c) + 1;
}
lastSeen.put(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}Smallest subarray with sum ≥ target#
def min_subarray_len(target: int, nums: list[int]) -> int:
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target: # valid → try to shrink
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
print(min_subarray_len(7, [2, 3, 1, 2, 4, 3])) # 2 ([4, 3])This shrink logic assumes adding elements only increases the sum. With negative numbers, shrinking might make the sum larger, so the window approach fails. Use prefix sums with a hash map, or Kadane's algorithm for maximum sums, instead.
Longest substring with at most K distinct characters#
from collections import defaultdict
def longest_k_distinct(s: str, k: int) -> int:
counts = defaultdict(int)
left = best = 0
for right, ch in enumerate(s):
counts[ch] += 1
while len(counts) > k: # too many distinct chars
counts[s[left]] -= 1
if counts[s[left]] == 0:
del counts[s[left]]
left += 1
best = max(best, right - left + 1)
return best
print(longest_k_distinct("eceba", 2)) # 3 ("ece")The universal template#
def sliding_window(arr):
state = ... # sum, counter, set, etc.
left = 0
answer = ...
for right in range(len(arr)):
add(arr[right], state) # 1. expand
while not valid(state): # 2. shrink until valid
remove(arr[left], state)
left += 1
answer = update(answer, left, right) # 3. record
return answerFor "longest" problems, update the answer after shrinking. For "shortest" problems, update it inside the shrink loop while the window is still valid.
Hard problem: minimum window substring#
Find the smallest substring of s that contains every character of t (with multiplicity).
from collections import Counter
def min_window(s: str, t: str) -> str:
need = Counter(t)
missing = len(t)
left = start = 0
best_len = float("inf")
for right, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0: # window has everything
if right - left + 1 < best_len:
best_len, start = right - left + 1, left
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1
left += 1
return "" if best_len == float("inf") else s[start:start + best_len]
print(min_window("ADOBECODEBANC", "ABC")) # "BANC"Sliding window maximum with a deque#
To get the maximum of every window of size k in O(n), keep a deque of indices whose values are decreasing:
from collections import deque
def max_sliding_window(nums, k):
dq, result = deque(), []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop() # smaller values can never be the max
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # out of the window
if i >= k - 1:
result.append(nums[dq[0]])
return result
print(max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3)) # [3, 3, 5, 5, 6, 7]Complexity summary#
| Problem | Brute force | Sliding window |
|---|---|---|
| Max sum of size k | O(n·k) | O(n) |
| Longest substring without repeats | O(n³) | O(n) |
| Minimum window substring | O(n² · m) | O(n + m) |
| Sliding window maximum | O(n·k) | O(n) |
Practice problems#
- Maximum Average Subarray I (LeetCode 643)
- Longest Substring Without Repeating Characters (3)
- Minimum Size Subarray Sum (209)
- Find All Anagrams in a String (438)
- Longest Repeating Character Replacement (424)
- Permutation in String (567)
- Minimum Window Substring (76)
- Sliding Window Maximum (239)
Sliding window relies on hash maps, counters and deques; see Python collections for a refresher, and binary search for the other must-know array pattern.
Key takeaways#
- Use sliding window for problems about contiguous subarrays or substrings.
- Fixed windows add one element and remove one each step; variable windows expand with
rightand shrink withleft. - Each element enters and leaves the window once, giving O(n) time.
- Track window state with a running sum, hash map, Counter or deque.
- The shrink-when-invalid approach needs a monotonic condition; it fails with negative numbers in sum problems.