Why Sliding Window?
From O(n^2) to O(n)
The sliding window technique transforms brute-force nested loops into a single pass through the data. It is one of the most frequently tested interview patterns.
When to Use It
Any time you need to find or compute something among contiguous subarrays or substrings of a given size (or satisfying a condition), sliding window is your go-to pattern.
Interview Frequency
Sliding window problems appear in roughly 15-20% of coding interviews at top companies. Mastering this pattern covers a huge chunk of array/string questions.
Two Types of Sliding Windows
1. Fixed-Size Window
Window size k is given. Slide it one element at a time.
Example: "Max sum subarray of size k"
Add the new element entering the window, remove the element leaving.
2. Variable-Size Window
Window size changes dynamically based on a condition.
Example: "Longest substring without repeating characters"
Expand right pointer, shrink left pointer when condition breaks.
Sliding Window Visualized
Fixed-Size Window Template
Classic Problem 1: Maximum Sum Subarray of Size K
Step-by-Step Window State (k=3)
Variable-Size Window Template
Classic Problem 2: Longest Substring Without Repeating Characters
Classic Problem 3: Minimum Window Substring (Hard)
Classic Problem 4: Fruits Into Baskets (Max 2 Distinct Characters)
Step-by-Step: Longest Substring Without Repeating Characters
Pattern Recognition: When to Use Sliding Window
Sliding Window Checklist
- The problem involves a contiguous subarray or substring
- You need to find max/min/count of something in a window
- The brute force involves two nested loops over the array
- Keywords: "subarray", "substring", "contiguous", "consecutive", "window of size k"
- The constraint can be checked by adding/removing one element at a time
Use Fixed Window When...
- ✅ Window size is given (k)
- ✅ "Maximum average subarray of length k"
- ✅ "All anagrams of pattern in string"
- ✅ "Max of all subarrays of size k"
Use Variable Window When...
- ✅ "Longest/shortest substring with condition"
- ✅ "Minimum window containing all characters"
- ✅ "Longest subarray with at most K distinct"
- ✅ "Smallest subarray with sum >= target"
Deep Dives
Deep Dive 1: String Windows vs Array Windows
String windows typically use a hash map or frequency counter to track character counts. Array windows may use running sums, deques (for max/min), or other structures.
- Strings: Use
Counterordefaultdict(int)to track frequencies. Comparing against a "need" map is the standard pattern for substring matching. - Arrays: Running sum works for sum-based problems. For max/min in window, use a monotonic deque for O(n) instead of O(n*k).
Deep Dive 2: Optimization Tricks
- Early termination: If the remaining elements cannot beat the current best, stop.
- Hash map optimization: Instead of deleting keys with count 0, check
if count > 0to avoid overhead. - Two pointers as sliding window: Many two-pointer problems (e.g., container with most water) are variants of the sliding window concept.
- Monotonic deque: For "sliding window maximum" use a deque maintaining decreasing order -- gives O(n) overall.
Common Mistakes
Mistake #1: Off-by-One Errors
Mistake #2: Forgetting to Shrink the Window
Practice Problems
Easy: Maximum Average Subarray I (LeetCode 643)
Given an array of n integers, find the contiguous subarray of length k that has the maximum average value.
Hint
Fixed window of size k. Track running sum, divide by k at the end.
Medium: Longest Repeating Character Replacement (LeetCode 424)
Given a string and integer k, find the length of the longest substring where you can replace at most k characters to make all characters the same.
Hint
Variable window. Track the count of the most frequent character. Window is valid when window_size - max_freq <= k.
Hard: Substring with Concatenation of All Words (LeetCode 30)
Find all starting indices where the concatenation of all words in a list exactly matches a substring.
Hint
Fixed window of size len(words) * len(words[0]). Use a word-level sliding window with two hash maps.
Quick Reference Guide
Key Takeaways
- Fixed window = given size k, slide one element at a time. O(n).
- Variable window = expand right, shrink left when condition breaks. O(n).
- Always ask: "Is this a contiguous subarray/substring problem?" If yes, try sliding window first.
Related Topics
Time Complexities
- Fixed Window: O(n)
- Variable Window: O(n) -- each element added/removed at most once
- Brute Force (nested loops): O(n*k) or O(n^2)