Part 2 - Mastering Sliding Window: Learning to Recognize the Pattern Before Writing Code
Part 2 applies the SPARK framework to Sliding Window. Instead of memorizing code, you will learn how to recognize the pattern from signals, properties, assumptions, traps, and interview reasoning.
Context
Why This Matters
Sliding Window is one of the most overused and misunderstood coding interview patterns. Candidates often see subarray or substring and jump directly to code. This article teaches the safer path: prove contiguity, prove overlap, prove incremental update, and then decide whether Sliding Window is enough. The goal is not to make you recite a template. The goal is to help you answer the interviewer's real question: why did you choose Sliding Window instead of another pattern?
Interviewers want to know whether you can identify contiguity, overlap, incremental state, and assumptions before choosing Sliding Window.
From the workplace
The Story You Will Remember
A candidate once saw Minimum Size Subarray Sum and immediately said Sliding Window. That was correct only because the numbers were positive. When the interviewer changed the problem to allow negative numbers, the candidate's logic broke. The issue was not the code; it was the missing assumption. Sliding Window was not chosen because the word subarray appeared. It was chosen because positive numbers made expansion and shrinking predictable.
Key takeaways
- Sliding Window is about contiguous overlap and reusable state.
- Positive signals are helpful, but assumptions decide.
- Subarray is not enough; pair, subset, graph, and tree usually point elsewhere.
- Many real solutions are hybrids: Sliding Window plus HashMap or Deque.
- Part 3 will show how ordered data leads naturally to Two Pointers.
Deep practical guide
Understanding Part 2 - Mastering Sliding Window: Learning to Recognize the Pattern Before Writing Code
Start here: what you will learn in this article
This article continues the SPARK series by applying the framework to one specific pattern: Sliding Window. You will not start with code. You will learn how to recognize the pattern before implementation. By the end, you should be able to explain why a problem is or is not a Sliding Window problem, how to compare it against HashMap, Prefix Sum, Kadane's Algorithm, Two Pointers, and Deque, and what assumptions make the pattern valid. If Part 1 taught you how to think before coding, this article teaches you how to use that thinking for contiguous range problems.
Workplace example
Think of this as going from a general debugging framework to one specific debugging playbook. Part 1 taught the triage method. Part 2 applies it to the recurring interview situation where a sequence has overlapping contiguous regions.
Tradeoff to manage: The article is long because Sliding Window is often overused. The first three sections give you the practical decision process; the later sections give traps, conversations, and practice calibration.
Exact wording
“After this article, I should be able to say why Sliding Window fits, not just recognize the name.”
“My goal is to identify contiguous overlap and validate assumptions before writing code.”
Quick recap: SPARK from Part 1, applied to Sliding Window
In Part 1, the thinking path was Problem, Signals, Properties, Candidate Patterns, Verify Assumptions, Choose Pattern, Algorithm, Code. We are not repeating the full framework here. We are applying it. For Sliding Window, the signals are words like subarray, substring, consecutive, continuous, window of size K, longest, shortest, at most K, at least K, and fixed-size K. The properties are contiguity, overlap between neighboring ranges, and state that can be updated incrementally. The candidate pattern becomes Sliding Window only after those properties and assumptions are present.
Workplace example
A senior engineer does not use the same debugging method for every incident. They apply the general framework differently depending on the shape of the system. Sliding Window is the SPARK framework applied to sequences with overlapping contiguous regions.
Tradeoff to manage: A short recap keeps continuity with Part 1 without delaying the useful content. Readers who need the full framework can revisit the previous article.
Exact wording
“The signal is substring, the property is contiguity, and the candidate pattern is Sliding Window only if the window state can be maintained.”
“I am not choosing Sliding Window because the word subarray appears; I am choosing it because neighboring ranges overlap and can reuse work.”
Why Sliding Window exists: reuse previous work
Sliding Window exists because many adjacent ranges share most of their elements. If you need the sum of every K consecutive elements, brute force recomputes almost the same sum again and again. For example, Window 1 might contain [2, 5, 1]. Window 2 contains [5, 1, 8]. Two elements stayed, one left, and one entered. The key idea is to subtract the leaving value and add the entering value instead of recomputing the entire range. Sliding Window is not a coding trick. It is an optimization technique that reuses previous work while moving across a contiguous region.
Workplace example
Imagine a monitoring dashboard that recalculates the last five minutes of traffic every second. A better system reuses the previous calculation, removes expired data, and adds the newest event. That is Sliding Window thinking in production form.
Tradeoff to manage: Reusing work is powerful only when the next state differs predictably from the previous state. If updates are not predictable, another pattern may be safer.
Exact wording
“The neighboring windows overlap, so I can reuse the previous window's state instead of recalculating from scratch.”
“Only one element leaves and one enters, so the window update is cheap.”
What problem Sliding Window actually solves
Sliding Window solves problems where you maintain information about a contiguous region while moving through a sequence. The sequence may be an array, string, or sometimes a stream. The maintained information could be a sum, count, frequency map, maximum, minimum, number of distinct characters, or whether the current window is valid. The important part is not the data structure used inside the window. The important part is the property: a continuous region changes gradually as pointers move.
Workplace example
A train window passing scenery is a good analogy. The view changes continuously. Most of the previous scene remains for a moment, then one part leaves and another enters. You do not rebuild the whole scene from memory.
Tradeoff to manage: The window can be fixed-size or variable-size. Fixed-size windows are simpler. Variable-size windows require a validity condition that tells you when to expand and when to shrink.
Exact wording
“Sliding Window is a pattern for maintaining state over a moving contiguous region.”
“The hash map is a helper here; the pattern is the moving window.”
SPARK walkthrough: longest substring without repeating characters
Problem: find the length of the longest substring without repeating characters. Signals: substring, longest, distinct characters. Properties: substring means contiguous; longest means optimization; distinct characters means the current region must remain valid. Candidate patterns: Sliding Window with HashMap or HashSet, brute force, and possibly dynamic programming. Reasoning: because the answer is a contiguous region and duplicates can be tracked as the window expands, we can move the right pointer to grow and move the left pointer to restore validity. Key assumptions: the data is ordered as a string, window validity can be checked incrementally, and removing characters from the left eventually restores validity.
Workplace example
This is like a magnifying glass reading a page. The lens shows a continuous set of characters. When a repeated character appears, you slide the left edge until the visible region becomes valid again.
Tradeoff to manage: The HashMap is necessary for fast duplicate tracking, but it does not replace Sliding Window. The algorithm is a hybrid: Sliding Window for movement and HashMap or HashSet for state.
Exact wording
“Substring is the strongest signal because it tells me the answer is contiguous.”
“I need a helper map to track duplicates, but the pattern is Sliding Window because the valid region grows and shrinks.”
Positive signals that support Sliding Window
Strong positive signals include subarray, substring, consecutive, continuous, contiguous sequence, window of size K, fixed-size K, longest, shortest, at most K, and at least K. Each signal matters because it points toward a continuous section of a sequence or an optimization over neighboring ranges. Subarray and substring imply contiguity. Fixed-size K implies the window length is known. At most K and at least K imply a validity boundary. Longest and shortest imply the window may expand or shrink to optimize a value. These signals do not prove Sliding Window by themselves, but they make it a serious candidate.
Workplace example
If a product analyst asks for rolling seven-day active users, the phrase rolling is a positive signal. The data is time-ordered, the range is contiguous, and each new day overlaps heavily with the previous range.
Tradeoff to manage: Positive signals must still be tested against assumptions. Subarray plus negative numbers may push you toward Prefix Sum. Window maximum may need a Deque. Product problems may need extra handling for signs and zeros.
Exact wording
“Subarray gives me contiguity, but I still need to check whether the window can be updated safely.”
“At most K suggests a validity rule that may allow a variable-size window.”
Negative signals that usually eliminate Sliding Window
Negative signals include pair, subset, any two elements, graph, tree, random indices, all permutations, disconnected nodes, and arbitrary choices. These usually eliminate Sliding Window because they do not require a contiguous region. Two Sum is about any pair, not adjacent or continuous values. Subset is about selecting elements, not preserving sequence continuity. Graph and tree problems are about connectivity or hierarchy, not a moving range. Permutations are about arrangements, not a single continuous region unless the problem also says substring.
Workplace example
If the task is to find any two employees whose skills complement each other, you do not scan only neighboring employees in a list. The relationship is not contiguous. You need lookup, sorting, matching, or graph modeling.
Tradeoff to manage: Some problems combine signals. Permutation in String contains permutation, but substring is the stronger signal because the permutation must appear inside a contiguous region of another string.
Exact wording
“Pair does not mean contiguous, so Sliding Window is not justified yet.”
“Permutation alone suggests generation or frequency comparison, but permutation inside a substring can become Sliding Window with frequency counts.”
Sliding Window assumptions most tutorials skip
Sliding Window depends on assumptions. First, the target region must be contiguous. Second, neighboring windows must overlap enough to reuse state. Third, the state must be updateable as one element enters or leaves. Fourth, variable windows need a validity condition that can be restored by moving one pointer. Fifth, some sum problems require positive numbers because positive values make expansion and shrinking predictable. When these assumptions fail, the Sliding Window label becomes dangerous. This is why subarray alone is not enough.
Workplace example
A moving average works because the next window differs in a predictable way. A random sample does not have that property. The same distinction applies to interview problems.
Tradeoff to manage: Calling out assumptions can feel cautious, but it makes the interviewer trust your reasoning. You are showing when the solution works and when it fails.
Exact wording
“This works because expanding the window changes the state predictably and shrinking can restore validity.”
“If negative numbers break the monotonic behavior, I would reconsider and use Prefix Sum instead.”
Common interview traps: when Sliding Window is not enough
Maximum Product Subarray contains subarray, but product behavior changes with negative numbers and zeros; Sliding Window alone is not enough. Maximum Sum Subarray is often Kadane's Algorithm, not a classic window, because the best start may reset based on cumulative value. Two Sum contains pair, which is not contiguous, so HashMap or sorting plus Two Pointers is stronger. Permutation in String contains permutation, but substring is the stronger signal; a fixed-size Sliding Window with frequency counts may work. Sliding Window Maximum uses a window, but the maximum cannot be maintained by simple add and remove; a Deque is needed. Minimum Size Subarray Sum works cleanly with positive numbers because sum movement is predictable.
Workplace example
These traps resemble production incidents where the first tool sounds right but lacks one missing capability. The pattern gets you close, but a helper structure or different algorithm may be required.
Tradeoff to manage: Hybrid solutions are common. Sliding Window plus HashMap, Sliding Window plus Deque, or Prefix Sum plus HashMap are all valid when the reasoning supports them.
Exact wording
“Sliding Window is a candidate, but the helper structure decides whether it is sufficient.”
“The word subarray gives me contiguity, not the full algorithm.”
Decision tree for choosing Sliding Window
Start with one question: is the answer based on a contiguous region? If no, reconsider. If yes, ask whether neighboring ranges overlap. If no, Sliding Window may not help. If yes, ask whether the window size is fixed. Fixed-size windows usually support simple add/remove updates. If the window is variable, ask whether there is a validity condition that can be restored by moving the left pointer. If the problem involves sums, inspect whether values are positive or whether negative values break predictable movement. If the window needs maximum or minimum, ask whether a Deque or heap is needed.
Workplace example
This is like triaging a performance issue with a checklist. You avoid jumping to Redis, indexes, or queues until the evidence says which lever fits.
Tradeoff to manage: Decision trees are not laws. They are guardrails that help you ask the right questions quickly under interview pressure.
Exact wording
“My decision tree starts with contiguity. If the answer is not contiguous, I should not force Sliding Window.”
“If this is a fixed K window, I can likely update by removing the outgoing element and adding the incoming one.”
Real interview conversations: explaining the choice
Conversation 1. Interviewer: Why Sliding Window? Candidate: Because the answer is a substring, so it must be contiguous, and I can maintain the validity of the current substring as pointers move. Conversation 2. Interviewer: Why not HashMap alone? Candidate: HashMap tracks state, but the moving contiguous region is the real pattern. Conversation 3. Interviewer: What assumption matters? Candidate: Moving the left pointer must eventually restore validity. Conversation 4. Interviewer: Would this work with negative numbers? Candidate: Not always; for sum problems I would consider Prefix Sum. Conversation 5. Interviewer: Is Two Sum Sliding Window? Candidate: No, pair does not imply contiguity. Conversation 6. Interviewer: What about fixed K? Candidate: Fixed K is the simplest Sliding Window because one element leaves and one enters each step. Conversation 7. Interviewer: What if we need max in each window? Candidate: Sliding Window gives the region, but Deque maintains the max efficiently. Conversation 8. Interviewer: Why not sort? Candidate: Sorting would destroy original contiguous order. Conversation 9. Interviewer: What makes the window valid? Candidate: The constraint, such as at most K distinct characters or sum at least target. Conversation 10. Interviewer: When would you abandon Sliding Window? Candidate: When the answer is not contiguous or the window state cannot be updated predictably.
Workplace example
These conversations are similar to design review. A strong engineer does not only name a tool; they explain why it fits and what would make them change course.
Tradeoff to manage: You do not need to say all ten conversations in one interview. Use the one that matches the interviewer question.
Exact wording
“HashMap is the state helper; Sliding Window is the movement pattern.”
“I would abandon Sliding Window if contiguity or incremental validity does not hold.”
Guided pattern recognition practice
Classify these before solving: longest substring without repeating characters; maximum sum subarray; minimum size subarray sum with positive numbers; subarray sum equals K with negative numbers; permutation in string; sliding window maximum; two sum in unsorted array; longest repeating character replacement; find all anagrams in a string; maximum average subarray of size K; longest subarray with at most K zeros; count good substrings of length three; shortest path in a binary matrix; number of islands; maximum product subarray; longest consecutive sequence; fruit into baskets; fixed-size K sum; smallest range covering elements from K lists; longest substring with at most K distinct characters. For each, identify signals, properties, candidate patterns, chosen pattern, and assumptions. The goal is classification, not code.
Workplace example
This is deliberate practice. You are training the recognition muscle separately from implementation so that interviews feel less like guessing.
Tradeoff to manage: Do not reveal answers too early during practice. Make yourself write the signals and assumptions first, then compare against explanations.
Exact wording
“I am practicing classification first: signals, properties, candidate patterns, chosen pattern, assumptions.”
“If I cannot name the assumption, I am not ready to code yet.”
Real-world analogies that make Sliding Window memorable
A camera moving across a football field captures a continuous slice of the action. A magnifying glass reading a page shows a continuous group of characters. A train window passing scenery keeps most of the scene for a moment, then gradually replaces it. A moving spotlight on a stage illuminates a continuous region while performers enter and leave the light. Each analogy captures the same essence: the region is contiguous, the region moves, and previous work can be reused rather than rebuilt from scratch.
Workplace example
Rolling metrics, streaming counters, fraud checks over recent activity, and dashboard time windows all use the same mental model: maintain state over a moving contiguous range.
Tradeoff to manage: Analogies help memory, but interviews require precision. Always connect the analogy back to contiguity, overlap, and incremental update.
Exact wording
“The moving camera analogy works because the window is continuous and changes gradually.”
“I can reuse previous state because only part of the view changes.”
One-page mental checklist before selecting Sliding Window
Before choosing Sliding Window, ask: Is the data sequence-based? Is the answer contiguous? Is there overlap between neighboring ranges? Can previous work be reused? Is the window fixed-size or variable-size? If variable-size, what condition makes the window valid or invalid? Can I expand and shrink incrementally? Do negative values, products, or random indices break assumptions? Is another candidate pattern better: Prefix Sum, HashMap, Two Pointers, Kadane's Algorithm, BFS, DFS, Deque, or Dynamic Programming? If you can answer these questions, your pattern choice will sound deliberate and interview-ready.
Workplace example
This checklist is your pre-flight check. It prevents you from taking off with a pattern that cannot land safely.
Tradeoff to manage: The checklist should take less than two minutes. If it takes longer, pick the strongest assumption and move forward while explaining uncertainty.
Exact wording
“The data is contiguous, neighboring ranges overlap, and I can update the state incrementally, so Sliding Window is justified.”
“Another pattern may exploit the data better, so I will compare before committing.”
Supporting framework
SPARK for Sliding Window
Signals
Look for language that implies a continuous range in an array or string.
Properties
Translate signals into contiguity, overlap, and incremental state.
Available Patterns
Compare Sliding Window with close alternatives.
Reasoning
Explain why the moving window remains valid and efficient.
Key Assumptions
Name what must be true for Sliding Window to work.
Words in the room
Useful Dialogue Examples
Bad
“Interviewer: Why Sliding Window? Candidate: Because the problem says subarray.”
Good
“Interviewer: Why Sliding Window? Candidate: Because the answer is contiguous, neighboring ranges overlap, and the current state can be updated as the window moves.”
Manager
“Interviewer: Why not HashMap? Candidate: HashMap tracks frequency, but the window controls which contiguous region is currently valid.”
SeniorEngineer
“Interviewer: What assumption matters? Candidate: For sum problems, positive numbers may be required so expansion and shrinking behave predictably.”
Leadership
“Interviewer: When would you switch patterns? Candidate: If contiguity disappears or incremental validity breaks, I would consider Prefix Sum, HashMap, Kadane's Algorithm, or another pattern.”
Avoid these traps
Common Mistakes
Choosing Sliding Window from the word subarray alone
Why it failsSubarray means contiguous but does not prove predictable updates.
Better approachCheck overlap, update rules, and assumptions before selecting the pattern.
Ignoring negative numbers
Why it failsNegative values can make sums non-monotonic and break shrink/expand logic.
Better approachUse Prefix Sum or another pattern when monotonic behavior disappears.
Treating HashMap as the pattern
Why it failsHashMap may only be the helper that tracks state inside the window.
Better approachSeparate movement pattern from state structure.
Using Sliding Window for Pair problems
Why it failsPair usually means a relationship between two values, not contiguity.
Better approachConsider HashMap or Two Pointers depending on ordering.
Forgetting Deque for window maximum
Why it failsSimple add/remove does not preserve the maximum efficiently.
Better approachUse a monotonic Deque when the window needs max or min queries.
Change your altitude
IC vs Manager vs Leader
| Situation | Individual Contributor | Manager | Leader |
|---|---|---|---|
| The prompt says subarray. | Confirms contiguity and checks constraints. | Looks for explanation of assumptions before code. | Evaluates whether the candidate can avoid keyword-driven decisions. |
| The prompt changes to include negative numbers. | Reconsiders simple Sliding Window. | Values the ability to adapt pattern choice. | Sees assumption-aware reasoning under changing requirements. |
Interview coaching
How to Answer in an Interview
Junior answer
I would choose Sliding Window when I see a contiguous range and can update the window as I move through the array or string.
MidLevel answer
I would first confirm the answer is contiguous, then check whether neighboring windows overlap and whether the window remains valid through incremental updates.
Senior answer
I would compare Sliding Window against Prefix Sum, HashMap, Kadane's Algorithm, Two Pointers, or Deque, then choose it only if contiguity and update assumptions hold.
Leadership answer
I would evaluate whether the candidate can explain not just how Sliding Window works, but when it fails and which alternative pattern handles the broken assumption.
Test your judgment
Practice Scenarios
Try firstClassify longest substring without repeating characters using signals, properties, candidate patterns, chosen pattern, and assumptions.
Review answer
Signals
substring and longest.
Properties
contiguous region with a validity rule, no repeated characters.
Candidate Patterns
Sliding Window with HashSet or HashMap, brute force. Choose variable-size Sliding Window.
Assumptions
moving the left pointer can remove duplicates and restore validity.
Try firstClassify maximum sum subarray and compare Kadane's Algorithm with Sliding Window.
Review answer
Signals
subarray, but the useful behavior is not a fixed or validity-restored window.
Candidate Patterns
Kadane's Algorithm and Sliding Window. Choose Kadane's Algorithm because the best running segment may reset when the current sum becomes harmful.
Assumptions
we are optimizing a running sum, not maintaining a window against a shrink rule.
Try firstClassify minimum size subarray sum with positive numbers and identify the key assumption.
Review answer
Signals
subarray, minimum length, target sum.
Properties
contiguous region with a shrink condition. Choose variable-size Sliding Window because all numbers are positive, so expanding increases the sum and shrinking decreases it predictably.
Assumptions
positivity creates monotonic behavior.
Try firstClassify subarray sum equals K with negative numbers and explain why Sliding Window may fail.
Review answer
Signals
subarray, but negative numbers break monotonic movement.
Candidate Patterns
Sliding Window and Prefix Sum. Choose Prefix Sum with HashMap because shrinking or expanding does not reliably move the sum toward K.
Assumptions
prefix differences can count valid ranges regardless of sign.
Try firstClassify permutation in string and identify whether permutation or substring is the stronger signal.
Review answer
Signals
permutation appears, but the requirement is whether it appears inside a substring.
Properties
fixed-length contiguous region with frequency matching. Choose fixed-size Sliding Window with frequency counts.
Assumptions
the candidate substring length equals the pattern length.
Try firstClassify sliding window maximum and explain why Deque is needed.
Review answer
Signals
window of size K.
Properties
fixed contiguous window, but maximum is not maintained by simple add and remove. Choose Sliding Window plus a monotonic Deque.
Assumptions
the Deque keeps only useful maximum candidates in window order.
Try firstClassify Two Sum and explain why pair is not contiguous.
Review answer
Signals
pair or any two elements.
Properties
no contiguous region is required. Choose HashMap lookup, or Two Pointers if the array is sorted and indices are not the main concern.
Assumptions
complement lookup or sorted movement matches the requirement better than a window.
Try firstClassify fruit into baskets as a variable window problem.
Review answer
Signals
longest contiguous segment with at most two types.
Properties
validity depends on frequency counts inside the current region. Choose variable-size Sliding Window with a frequency map.
Assumptions
removing fruit types from the left can restore the at-most-two constraint.
Try firstClassify maximum average subarray of size K as fixed-size window.
Review answer
Signals
subarray of size K.
Properties
every candidate range has the same fixed length and neighboring ranges overlap. Choose fixed-size Sliding Window.
Assumptions
each move removes one outgoing value and adds one incoming value.
Try firstClassify number of islands and explain why graph traversal wins.
Review answer
Signals
grid connectivity.
Properties
connected components, not a one-dimensional contiguous range. Choose DFS or BFS.
Assumptions
adjacency traversal is the core operation.
Try firstClassify contains duplicate II and decide whether it is fixed-size window or HashSet tracking.
Review answer
Signals
duplicate within distance K.
Properties
only the last K indices matter. Choose a fixed-size Sliding Window with a HashSet.
Assumptions
values outside distance K can be safely removed.
Try firstClassify longest repeating character replacement as variable-size Sliding Window.
Review answer
Signals
longest substring with at most K replacements.
Properties
the current window is valid if window length minus max character frequency is at most K. Choose variable-size Sliding Window with counts.
Assumptions
the max frequency lets you test whether the window can be made uniform.
Try firstClassify find all anagrams in a string as fixed-size Sliding Window with frequency counts.
Review answer
Signals
anagrams inside a string.
Properties
each candidate substring has fixed length equal to the pattern. Choose fixed-size Sliding Window with frequency comparison.
Assumptions
anagrams can be recognized by character counts.
Try firstClassify best time to buy and sell stock and compare it with window-style reasoning.
Review answer
Signals
ordered days and best profit, but no fixed contiguous answer range is requested. Choose one-pass tracking of minimum price and best profit. It resembles window movement, but the pattern is better explained as maintaining a best prior candidate.
Assumptions
buy day must come before sell day.
Try firstClassify shortest subarray with sum at least K when negatives are allowed.
Review answer
Signals
shortest subarray, but negatives break simple Sliding Window. Choose Prefix Sum plus a monotonic Deque.
Assumptions
prefix order and deque maintenance are needed because sums are not monotonic.
Try firstClassify longest subarray with at most K zeros.
Review answer
Signals
longest contiguous range with at most K invalid items. Choose variable-size Sliding Window.
Assumptions
when zero count exceeds K, moving left can restore validity.
Try firstClassify maximum product subarray and explain why product sign changes matter.
Review answer
Signals
subarray, but products with negatives and zeros change direction. Choose DP-style tracking of max and min product ending here.
Assumptions
the minimum product can become maximum after multiplying by a negative value.
Try firstClassify merge intervals and explain why it is not Sliding Window.
Review answer
Signals
intervals, overlap.
Properties
the operation is sorting and merging ranges, not moving a contiguous window over indices. Choose sorting plus interval merge.
Assumptions
sorted starts let you compare each interval with the current merged interval.
Try firstClassify binary tree level order traversal and explain why traversal wins.
Review answer
Signals
tree levels.
Properties
hierarchical connectivity, not contiguous array or string regions. Choose BFS with a queue.
Assumptions
queue order preserves level-by-level traversal.
Try firstClassify longest consecutive sequence and explain why contiguous values are not the same as contiguous indices.
Review answer
Signals
consecutive values, but values may appear at random indices. Choose HashSet expansion from sequence starts.
Assumptions
membership lookup matters more than preserving array order.
Choose the next move
Decision Tree
If the answer is not contiguous
→do not choose Sliding Window → consider HashMap, sorting, graph traversal, or DP
If the window size is fixed
→use fixed-size Sliding Window → remove outgoing and add incoming element
If the window size is variable but validity can be restored
→use variable-size Sliding Window → expand right and shrink left
If sum constraints include negative numbers
→reconsider simple Sliding Window → evaluate Prefix Sum
If max or min is needed per window
→combine Sliding Window with Deque → maintain monotonic candidates
If the prompt asks for any pair
→avoid Sliding Window → consider HashMap or Two Pointers
Short answers
Frequently Asked Questions
Use sliding window when the answer depends on a contiguous region, neighboring ranges overlap, and the useful state can be updated as one element enters and another leaves.
Was this article helpful?