Sliding Window Pattern
The Sliding Window pattern maintains a contiguous range of elements in an array or string and expands or contracts that range as it scans the input once. It replaces nested loops that re-scan the same subarray repeatedly, turning O(n^2) brute-force solutions into O(n) by reusing work between iterations.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Complexity
- Time
- O(n)
- Space
- O(k)
When to use Sliding Window
- The problem asks for a contiguous subarray or substring that satisfies a property (max sum, longest, shortest, count).
- Brute force would re-scan the same elements for every starting index.
- The property of the window can be maintained incrementally as one element enters and one leaves (sum, character count, distinct count).
- The window size is fixed (k) or variable based on a constraint that you can detect at the edges.
- You can answer the question by looking at the current window only, without backtracking.
Template
function variableSlidingWindow(s, constraint) {
let left = 0;
let best = 0;
const state = new Map();
for (let right = 0; right < s.length; right++) {
state.set(s[right], (state.get(s[right]) || 0) + 1);
while (!isValid(state, constraint)) {
state.set(s[left], state.get(s[left]) - 1);
if (state.get(s[left]) === 0) state.delete(s[left]);
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}Example LeetCode problems
| # | Problem | Difficulty | Frequency |
|---|---|---|---|
| 3 | Longest Substring Without Repeating Characters | medium | foundational |
| 76 | Minimum Window Substring | hard | company favorite |
| 424 | Longest Repeating Character Replacement | medium | frequently asked |
| 567 | Permutation in String | medium | frequently asked |
| 643 | Maximum Average Subarray I | easy | foundational |
| 239 | Sliding Window Maximum | hard | classic |
| 904 | Fruit Into Baskets | medium | frequently asked |
| 713 | Subarray Product Less Than K | medium | frequently asked |
Common mistakes
- Shrinking the window from the wrong side, breaking the contiguous-range invariant.
- Updating the running aggregate (sum, count) before deciding whether to record a new best, leading to off-by-one window sizes.
- Using a `for` loop on left instead of a `while`, which fails when multiple elements must leave for the window to become valid again.
- Forgetting to delete a key from the hash map when its count hits zero, which inflates the distinct-character count.
- Confusing fixed-size with variable-size sliding window templates and mixing the two control flows.
Frequently asked questions
What is the difference between fixed-size and variable-size Sliding Window?
Fixed-size keeps a window of exactly k elements and slides forward one step per iteration. Variable-size grows the right pointer every step and contracts the left pointer only when a constraint is violated, producing windows of changing lengths.
When should I use Sliding Window vs Two Pointers?
Sliding Window is the right choice when you need a contiguous range whose aggregate property determines the answer, and both pointers only move forward. Two Pointers fits sorted-array search problems where the pointers can move toward each other based on a comparison between endpoint values.
Why is the time complexity O(n) when there is a nested while loop?
Each element enters the window once when right advances and leaves at most once when left advances. The total work across both loops is bounded by 2n, which is still O(n) amortized.
Can Sliding Window handle negative numbers in a sum-based problem?
Not directly. The shrink condition assumes that removing an element from the left strictly decreases the running sum. With negatives, contracting may overshoot or never trigger, so most negative-number variants use a prefix-sum plus hash map approach instead.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill the Sliding Window pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →