Recognition guide
How to recognize a sliding window problem
A sliding window keeps a contiguous slice of an array or string and updates it as the ends move, instead of starting over from every position. That turns an O(n²) rescan into a single pass. The skill worth building is recognizing, from the wording alone, when a problem is asking for a window.
This guide covers the recognition step. For the mechanics, a complete worked example, and the step-by-step trace, see the Sliding Window pattern page.
What a window problem asks
Every sliding window problem is about a contiguous stretch of the input, and about some property of that stretch: its sum, its length, its set of characters, its counts. You are usually asked to find the longest, shortest, largest, or smallest slice that satisfies a rule.
Clues in the statement
- "Subarray" or "substring." Both mean the elements sit next to each other. This is the strongest clue. Without contiguity, there is no window.
- "Longest" or "shortest" segment that meets a condition. The answer is a length.
- "Of size k" or "k consecutive." A fixed-size window.
- "At most k distinct" or "no repeated characters." A rule about what is inside the slice.
- "Maximum sum of k consecutive elements." Slide one step: add the new value, drop the old one.
- "Within a budget." For example, a slice where you may change at most k characters.
Fixed or variable?
- Fixed: the width is given. Add the entering element, remove the leaving one, record the answer. There is no shrinking rule.
- Variable: the width is the answer. The window grows on the right. When the rule breaks, it shrinks on the left until the rule holds again. For a "longest" question, you record after it is valid. For a "shortest" question, you record while it is valid and keep shrinking.
The test that matters: can the state be updated in O(1)?
A window only pays off if adding one element and removing one element each change your running state cheaply: a sum, a count map, a distinct-character total. And the rule must behave sensibly as the window moves: when it is broken, removing from the left must be able to repair it, and when it holds, adding on the right must not secretly fix a different problem.
If you can say "add x, remove y, and I know the new state without rescanning," it is a window.
Counter-signals: look-alikes
- "Subsequence." Elements may be skipped, so a contiguous window will miss answers. That is usually dynamic programming.
- A target sum with negative numbers. Shrinking is no longer safe, because removing a value can make the sum bigger. Use a prefix sum with a hash map instead.
- A pair in a sorted row. Two ends closing in on a target are Two Pointers. See clues that a problem needs two pointers.
- "Count subarrays with exactly k of something." A single window struggles with "exactly". Count "at most k" and subtract "at most k − 1", or use a prefix-sum count.
- Anything that needs a value you cannot update when it leaves. A running maximum, for example, is not undone by removing an element. It needs extra structure such as a monotonic queue.
The decision checklist
- Is the answer about a contiguous subarray or substring?
- Is it asking for the longest, shortest, best, or a fixed-width slice?
- Can you update the state by adding one element and removing one?
- Does shrinking from the left move you toward a valid slice? With negative numbers in a sum, it does not.
- If it says "subsequence" or "any elements", stop. It is not a window.
If 1 to 3 are yes and 4 holds, write a window.
Three worked examples
1. "Find the maximum sum of any 3 consecutive readings."
Clues: "consecutive" and a width of 3. Fixed window: keep the running total, add the new reading, subtract the one that left, track the best.
Pattern: sliding window, fixed size.
2. "Return the length of the longest substring that has at most 2 distinct characters."
Clues: "substring", "longest", "at most 2 distinct". Keep a count per character. Grow on the right. When the number of distinct characters exceeds 2, shrink on the left and remove a character from the map when its count reaches zero.
Pattern: sliding window, variable size.
3. "All numbers are positive. Return the length of the shortest subarray whose sum is at least the target."
Clues: "shortest", "subarray", and positive values. Adding makes the sum grow and removing makes it shrink, so shrinking while the rule still holds is safe.
Pattern: sliding window, variable size.
TypeScriptfunction shortestAtLeast(nums: number[], target: number): number {let left = 0;let sum = 0;let best = Infinity;for (let right = 0; right < nums.length; right++) {sum += nums[right];while (sum >= target) {best = Math.min(best, right - left + 1);sum -= nums[left];left++;}}return best === Infinity ? 0 : best;}The idea applies in any language. Notice that leftonly ever moves forward, so the total work is O(n).If the same problem allowed negative numbers, clue 4 would fail, and a window would give wrong answers. That is the signal to reach for prefix sums.
Common traps
- Using a window when the values can be negative. A "sum equals k" problem with negatives is not a window problem.
- Shrinking with `if` instead of `while`. One removal may not be enough to repair the window.
- Forgetting to clean up state on removal. A count map entry that stays at zero makes the distinct count wrong.
- Off-by-one on the length. The window from
lefttorightinclusive hasright - left + 1elements. - Restarting from every index. If you rescan the slice each time, you have rebuilt the O(n²) solution the window was meant to avoid.
Quick answers
How is it different from two pointers?
Both use two indexes. A window moves both ends in one direction and the slice between them is the object. Two pointers usually close in on a target or compare the ends.
Does it work on strings?
Yes. A substring is just a contiguous slice, and a count map tracks what is inside.
What if I am not sure the rule is monotonic?
Try a tiny input by hand. If removing from the left can ever make a broken window more broken, the window will not work.
Practice it on Algofily
Algofily trains the recognition step before the code: each problem moves through Understand, Think, Code, and Explain. In the Code stage, Algofily AI can give progressive hints instead of the full solution (sign-in required).
- Work through the Sliding Window pattern page for a full trace and the problems that practice it, from a fixed-width sum up to a covering window.
While you code, Algofily AI can ask a question and open the next hint.