Sliding Window Interview Problems — Patterns, Code and Gotchas
- The subtract-and-add update is the entire reason sliding window is O(n) instead of O(n×k) — without it you're just doing brute force with extra steps
- Use while to shrink, never if — an if only evicts one element per expansion, but the window may need to contract multiple positions before it's valid again
- Maximum-length problems update the answer after the shrink phase; minimum-length problems update inside the shrink loop — mix these up and you'll get off-by-one errors that are very hard to debug under pressure
Imagine you're reading a very long receipt from a grocery store, and you need to find the 3 consecutive items that cost the most together. Instead of adding up every possible group of 3 from scratch, you slide a physical 'window' of 3 items across the receipt — dropping one item off the left and picking up one on the right as you go. That's it. A sliding window is just a moving frame over a sequence of data that lets you avoid redundant recalculations.
Sliding window problems show up in almost every technical interview at top-tier companies — not because they're obscure, but because they test whether you think algorithmically or just mechanically. The naive solution to most array and string problems is O(n²) nested loops. The sliding window technique collapses that to O(n), and interviewers use these problems specifically to see if you can make that leap without prompting.
The core problem it solves is this: any time you need to examine a contiguous subarray or substring under some constraint — maximum sum, longest without repeating characters, smallest with a target sum — you're repeatedly looking at overlapping data. Brute force recalculates that overlapping data every single iteration. A sliding window maintains just enough state so you only ever process each element once as the window expands and once as it contracts.
By the end of this article you'll be able to recognise which of the two main window types (fixed-size vs dynamic) applies to a given problem, implement both from memory, handle the edge cases that trip up even experienced candidates, and answer the follow-up questions interviewers use to separate good solutions from great ones.
Fixed-Size Windows — When the Frame Never Changes
A fixed-size window is the simpler of the two patterns. The window length is given to you upfront and never changes — your only job is to slide it across the array one step at a time and track whatever metric you care about.
The key insight is how you update the window in O(1) instead of O(k): when the window moves one position to the right, exactly one element leaves the left edge and one enters the right edge. That means you don't need to sum (or hash, or count) the whole window again — you just subtract the outgoing element and add the incoming one.
This pattern covers problems like: maximum average subarray of length k, maximum sum subarray of length k, count of anagram occurrences in a string, and find all substrings containing exactly k distinct characters with a fixed length.
The implementation template is always the same: build the first window, record your answer, then loop from index k to n-1, sliding by one each iteration. Get that template into muscle memory and the code almost writes itself.
package io.thecodeforge.algorithms; public class MaxSumFixedWindow { /** * Finds the maximum sum of any contiguous subarray of exactly 'windowSize' elements. * Time: O(n) — each element is added once and removed once * Space: O(1) — no extra data structures needed */ public static int findMaxSum(int[] prices, int windowSize) { int totalElements = prices.length; // Edge case: window is larger than the array itself if (windowSize > totalElements) { throw new IllegalArgumentException( "Window size " + windowSize + " exceeds array length " + totalElements ); } // Step 1: Build the first window by summing the first 'windowSize' elements int currentWindowSum = 0; for (int i = 0; i < windowSize; i++) { currentWindowSum += prices[i]; } // The first window is our baseline best answer int maxSum = currentWindowSum; // Step 2: Slide the window one position at a time across the rest of the array for (int rightEdge = windowSize; rightEdge < totalElements; rightEdge++) { int leftEdge = rightEdge - windowSize; // the element we're dropping off the left // Drop the outgoing element, add the incoming element — one operation each currentWindowSum += prices[rightEdge]; // new element entering from the right currentWindowSum -= prices[leftEdge]; // old element leaving from the left // Update our best answer if this window beats it maxSum = Math.max(maxSum, currentWindowSum); } return maxSum; } public static void main(String[] args) { int[] dailyStockPrices = {12, 5, 35, 8, 6, 14, 21, 9, 3, 18, 27, 11, 4, 16}; int targetWindowDays = 4; int result = findMaxSum(dailyStockPrices, targetWindowDays); System.out.println("Stock prices: " + java.util.Arrays.toString(dailyStockPrices)); System.out.println("Max 4-day sum: " + result); } }
Max 4-day sum: 57
Dynamic Windows — When the Frame Grows and Shrinks Based on a Condition
Dynamic (or variable-size) windows are where most candidates stumble, because the window doesn't have a fixed length — it grows until it violates a constraint, then shrinks from the left until it's valid again. The two-pointer approach drives this: a right pointer expands the window, and a left pointer contracts it.
The mental model that makes this click: think of the right pointer as greedy and optimistic — it keeps consuming elements hoping to satisfy or maximise the target. The left pointer is the enforcer — when the window breaks the rules, it evicts elements from the left until the window is valid again.
This pattern handles: longest substring without repeating characters, minimum size subarray with sum ≥ target, longest subarray with at most k distinct characters, and fruit into baskets (same idea, different flavour).
The critical implementation detail is the order of operations inside the loop: expand right first, update your state, then shrink left in a while loop until valid, then record your answer. Get that order wrong and you'll record invalid states or miss valid ones — a bug that's devilishly hard to spot under interview pressure.
package io.thecodeforge.algorithms; import java.util.HashMap; import java.util.Map; public class LongestSubstringKDistinct { /** * Finds the length of the longest substring with at most 'maxDistinct' distinct characters. * Time: O(n) — each pointer travels the array once * Space: O(k) — where k is the number of distinct characters allowed */ public static int findLongest(String text, int maxDistinct) { if (text == null || text.isEmpty() || maxDistinct == 0) return 0; Map<Character, Integer> charFrequencyInWindow = new HashMap<>(); int leftPointer = 0, longestFound = 0; for (int rightPointer = 0; rightPointer < text.length(); rightPointer++) { char incomingChar = text.charAt(rightPointer); charFrequencyInWindow.put(incomingChar, charFrequencyInWindow.getOrDefault(incomingChar, 0) + 1); // Shrink from the left until we're back to maxDistinct distinct chars while (charFrequencyInWindow.size() > maxDistinct) { char outgoingChar = text.charAt(leftPointer); charFrequencyInWindow.put(outgoingChar, charFrequencyInWindow.get(outgoingChar) - 1); if (charFrequencyInWindow.get(outgoingChar) == 0) { charFrequencyInWindow.remove(outgoingChar); } leftPointer++; } longestFound = Math.max(longestFound, rightPointer - leftPointer + 1); } return longestFound; } public static void main(String[] args) { String dnaSequence = "AABABCBCBAABC"; int result = findLongest(dnaSequence, 2); System.out.println("DNA sequence: " + dnaSequence); System.out.println("Longest valid substring length (2 distinct): " + result); } }
Longest valid substring length (2 distinct): 5
Recognising the Pattern Fast — The 3-Question Decision Framework
The hardest part of sliding window problems in an interview isn't the code — it's recognising within 60 seconds that sliding window is even the right tool. Interviewers watch this recognition moment closely.
Three questions will get you there every time. First: does the problem involve a contiguous subarray or substring? If the order doesn't matter or elements don't need to be adjacent, sliding window is the wrong tool — reach for a hash map or a sort instead. Second: is there a constraint on the window (sum ≥ target, at most k distinct, no repeating characters)? That constraint is what drives the window's expansion and contraction logic. Third: are you optimising for a minimum or maximum (shortest, longest, smallest, largest)? This tells you whether to update your answer after expanding (maximum) or after contracting (minimum).
For minimum problems — like smallest subarray with sum ≥ target — the trick is you shrink the window as aggressively as possible while still meeting the constraint, updating your best answer after each contraction, not after expansion.
package io.thecodeforge.algorithms; public class MinSizeSubarraySum { /** * Finds the minimum length of a contiguous subarray whose sum is >= targetSum. * Time: O(n) * Space: O(1) */ public static int minSubarrayLength(int[] nums, int targetSum) { int leftPointer = 0, currentWindowSum = 0; int minimumLength = Integer.MAX_VALUE; for (int rightPointer = 0; rightPointer < nums.length; rightPointer++) { currentWindowSum += nums[rightPointer]; // Update the answer INSIDE this loop — that's the minimum-problem pattern while (currentWindowSum >= targetSum) { minimumLength = Math.min(minimumLength, rightPointer - leftPointer + 1); currentWindowSum -= nums[leftPointer]; leftPointer++; } } return (minimumLength == Integer.MAX_VALUE) ? 0 : minimumLength; } public static void main(String[] args) { int[] nums = {2, 3, 1, 2, 4, 3}; int target = 7; System.out.println("Input: " + java.util.Arrays.toString(nums) + ", Target: " + target); System.out.println("Minimum length: " + minSubarrayLength(nums, target)); } }
Minimum length: 2
Production-Grade Implementation: Handling Stream Data
In real-world systems, data often arrives as a stream rather than a static array. For these cases, we use specialized data structures or reactive patterns. Below is how you would model a sliding window over a potentially infinite stream of integers using a standard Java queue to represent the window state.
package io.thecodeforge.algorithms; import java.util.LinkedList; import java.util.Queue; /** * Simulates a sliding window over a stream of data. * This mimics how production systems track rolling averages or rate limits. */ public class StreamSlidingWindow { private final int windowSize; private final Queue<Integer> window = new LinkedList<>(); private double runningSum = 0; public StreamSlidingWindow(int size) { this.windowSize = size; } public void addReading(int val) { window.add(val); runningSum += val; if (window.size() > windowSize) { runningSum -= window.poll(); } } public double getRollingAverage() { return window.isEmpty() ? 0 : runningSum / window.size(); } public static void main(String[] args) { StreamSlidingWindow throughputTracker = new StreamSlidingWindow(3); int[] streamData = {100, 200, 300, 400, 500}; for (int data : streamData) { throughputTracker.addReading(data); System.out.println("Added: " + data + " | Current Rolling Avg: " + throughputTracker.getRollingAverage()); } } }
Added: 200 | Current Rolling Avg: 150.0
Added: 300 | Current Rolling Avg: 200.0
Added: 400 | Current Rolling Avg: 300.0
Added: 500 | Current Rolling Avg: 400.0
| Aspect | Fixed-Size Window | Dynamic Window |
|---|---|---|
| Window size | Given as input — constant throughout | Determined by a constraint — varies per iteration |
| Pointers needed | One pointer (or index + offset) | Two explicit pointers (left and right) |
| Shrink logic | Automatic — always drops element at index (right - k) | Conditional — while loop runs until constraint satisfied |
| Answer update timing | After every slide (every iteration) | Max problems: after shrink. Min problems: inside shrink loop |
| State tracking | Simple running total or counter | Usually a HashMap or frequency array for the window's contents |
| Typical problem signal | 'subarray of length k' is in the problem statement | 'longest', 'shortest', 'at most k', 'no repeating' — flexible length |
| Example problems | Max sum of k elements, count anagrams | Longest substring without repeats, min subarray sum >= target |
| Time complexity | O(n) | O(n) — left pointer moves at most n times total across all iterations |
🎯 Key Takeaways
- The subtract-and-add update is the entire reason sliding window is O(n) instead of O(n×k) — without it you're just doing brute force with extra steps
- Use while to shrink, never if — an if only evicts one element per expansion, but the window may need to contract multiple positions before it's valid again
- Maximum-length problems update the answer after the shrink phase; minimum-length problems update inside the shrink loop — mix these up and you'll get off-by-one errors that are very hard to debug under pressure
- The 3-question check (contiguous? constrained? optimising min or max?) lets you identify a sliding window problem in under 30 seconds — interviewers notice when you name the pattern before touching the keyboard
⚠ Common Mistakes to Avoid
Interview Questions on This Topic
- QLongest Substring with at Most K Distinct Characters: Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters. (LeetCode #340)
- QSmallest Subarray with Sum Greater than S: Given an array of positive integers and a number ‘S’, find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. (LeetCode #209)
- QPermutation in String: Given two strings s1 and s2, return true if s2 contains a permutation of s1. How would you apply a fixed-size window to solve this efficiently? (LeetCode #567)
- QLongest Repeating Character Replacement: Given a string s and an integer k, you can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Find the length of the longest substring containing the same letter. (LeetCode #424)
- QSubarrays with Product Less Than K: Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. (LeetCode #713)
Frequently Asked Questions
What is the difference between a sliding window and two pointers?
Two pointers is the broader technique — it describes any algorithm using two indices that move through a data structure. Sliding window is a specific application of two pointers where the two indices define the edges of a contiguous subarray or substring and move in the same direction (both left to right). All sliding windows use two pointers, but not all two-pointer problems are sliding windows.
When should I use a sliding window versus a prefix sum array?
Use a sliding window when you need to find an optimal window (longest, shortest, maximum, minimum) under a dynamic constraint that changes as you scan — especially when the constraint depends on the content of the window, like distinct characters or no repeats. Use a prefix sum when you need to answer multiple arbitrary range-sum queries on a fixed array, since prefix sums let each query run in O(1) after O(n) preprocessing.
Why does my sliding window give wrong answers on arrays with negative numbers?
The standard dynamic sliding window assumes that adding more elements to the window can only make the sum larger (or at worst neutral), so you can always meaningfully expand right and contract left. Negative numbers break this assumption — shrinking the window might actually increase the sum, meaning the greedy expand-then-contract logic no longer guarantees you've found the optimal window. For arrays with negatives, Kadane's algorithm or a deque-based approach is usually the right tool instead.
Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.