Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

Coding Interview Patterns: How to Use the Sliding Window Invariant

A sliding window is only reliable when its maintained state and boundary movements preserve a clear invariant. Learn the interview patterns, proof checks, and cases where the template fails.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A sliding window is a way to maintain information about a contiguous range as its boundaries move—not a shortcut that applies to every subarray problem. Before coding, define the range, name the state it tracks, and state what must remain true after each update. Then justify why moving the left boundary can restore validity without skipping a better answer.

What a sliding window represents

For an array or string, a window is a contiguous range between two boundaries. You can describe it as the inclusive range [left, right]. The maintained state might be its sum, character frequencies, number of distinct values, or candidates for its maximum and minimum.

An invariant is the condition your algorithm keeps true at a specific point in the loop. For example: “The current range is [left, right], and the frequency map contains exactly the characters in that range.” If the algorithm requires a valid window, add the relevant condition: “After shrinking, the range has no repeated characters.” State the invariant in terms of the actual problem, not as a memorized template.

Correctness depends on two linked claims: the maintained state really describes the current range, and the rule for moving each boundary preserves or restores the required property. A familiar loop shape alone proves neither.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Cracking the Coding Interview: 189 Programming Questions and Solutions
  • Careercup, Easy To Read
  • Condition : Good
  • Compact for travelling

Choose the window pattern that matches the task

Pattern What to maintain Recognition cue Correctness check
Fixed-size window Exactly k elements and a summary of them Every subarray or substring of length k; one result per window Emit the first answer only when the window reaches length k; each slide removes the departing element’s contribution.
Variable window for a longest valid range A window satisfying an at-most or similar constraint after shrinking Longest range that meets a condition Update the best length only while the window is valid.
Variable window for a shortest covering range Coverage of required values or frequencies Smallest range containing required items Count multiplicities when required and record a valid candidate before shrinking makes it invalid.
Frequency-map window Counts for values in the current range, plus a validity measure such as distinct count Anagrams, permutations, duplicate-free strings, or at-most-K-distinct ranges Update counts on both entry and removal; distinguish distinct keys from total matching occurrences.
Monotonic deque Candidate indices ordered by their values and kept inside the window Maximum or minimum per window, or a constraint involving extrema Expire out-of-window indices, remove dominated candidates, and ensure the front is the current extremum.
Prefix sums plus a hash map Earlier prefix sums and their counts Exact target sum, especially when values may be negative Do not assume the sum moves monotonically when a boundary advances.

These patterns are not interchangeable. In particular, “longest,” “shortest,” and “count how many” are different objectives, and each needs an argument that the chosen boundary movements preserve the answers. LeetCode community tutorials describe several of these recurring families, including frequency maps, at-most/exactly-K constraints, and prefix-sum alternatives: LeetCode Discuss: Summary of Sliding Window Patterns and LeetCode Discuss: 10 Sliding Window Patterns for Coding Interviews.

Fixed-size windows: keep the length at k

A fixed-size window has a simple invariant: the current range contains exactly k elements, and the maintained summary describes those elements. LeetCode’s official Sliding Window Maximum statement defines a window of size k that moves from the left of the array to the right: LeetCode 239: Sliding Window Maximum.

Trace: sliding-window maximum

For nums = [1,3,-1,-3,5,3,6,7] and k = 3, the consecutive windows and their maxima are:

Window Maximum
[1, 3, -1] 3
[3, -1, -3] 3
[-1, -3, 5] 5
[-3, 5, 3] 5
[5, 3, 6] 6
[3, 6, 7] 7

The resulting output is [3,3,5,5,6,7]. Each answer belongs to one contiguous range of three values; advancing one position removes the old leftmost value and admits the next value on the right.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a running sum is enough

If the requested summary is a sum, calculate the first complete window, then update it by adding the entering value and subtracting the departing value. The invariant is that the running sum equals the sum of exactly the current k elements. This avoids recomputing every window from scratch.

Variable-size windows: expand and repair

For a common variable-window problem, advance right to include new data. If that makes the range invalid, advance left and remove the departing data from the maintained state until the required condition is restored. For a longest-valid-range problem, update the best answer only after validity is restored.

Example: longest substring without repeated characters

Maintain character frequencies for the inclusive range [left, right]. Add the newly included character. If it creates a duplicate, move left rightward, decrementing the frequency of each departing character, until no duplicate remains. Then the frequency map again describes a valid, duplicate-free window, so its length can be considered for the best answer.

The key is not merely that the loop shrinks when a duplicate appears. The invariant must say exactly what the counts represent, and removal must update those counts correctly. For an at-most-K-distinct condition, for example, track how many distinct keys have positive frequency; decrement that total only when a character’s frequency falls to zero.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why the left boundary can move forward

For a two-pointer solution to be sound, explain why the condition has the needed monotone behavior. In a duplicate-free substring, adding a character can introduce a duplicate; removing characters from the left can eventually remove that duplicate. When looking for a longest valid range, once a left-side start has been ruled out for the current right boundary, later right boundaries do not make that discarded start useful again. That reasoning supports moving left only forward.

This proof depends on the particular condition and objective. For shortest covering ranges, expand until all requirements are met, record the valid candidate, then shrink while coverage remains sufficient. If the requirements include repeated values, “covered” must account for the required multiplicities. Do not assume that a shrink rule is correct just because the problem mentions a subarray.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use a deque when the window needs its extrema

A sum or distinct-count total cannot by itself answer which value is largest or smallest in the current range. For repeated maximum or minimum queries, maintain candidate indices in a monotonic deque. For a maximum, keep values in decreasing order: remove expired indices from the front and remove smaller, dominated candidates from the back. The front then identifies the maximum in the current window. Store indices, rather than values alone, so the algorithm can determine when a candidate has left the range.

Each index is added once and removed at most once, either because it expires or because a later value dominates it. This gives amortized O(n) time and O(k) space for the sliding-window maximum method described by Doocs LeetCode Wiki.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The same principle applies to variable ranges whose validity depends on both maximum and minimum—for example, a condition involving max - min. Keep separate monotonic candidates for the maximum and minimum; a scalar sum or distinct count cannot determine those extrema.

When the ordinary sliding-window rule fails

Do not use “shrink while the sum is too large” for a target-sum problem without proving that the sum changes monotonically as the boundaries move. Negative values break the usual intuition: adding a value on the right can raise or lower the sum, and removing a value on the left can also move it in either direction. The boundary of valid ranges is therefore not reliably ordered by a simple expand-and-shrink rule.

Use prefix sums for Subarray Sum Equals K

Let prefix be the sum of the values seen so far. A subarray ending at the current position sums to k when an earlier prefix sum equals prefix - k. A hash map can store counts of earlier prefix sums; look up prefix - k to count matching subarrays, then record the current prefix for later positions. This approach handles negative values because it does not rely on the sum moving in one direction. The prefix-sum alternative is also discussed in the LeetCode Discuss pattern tutorial.

How to explain correctness and complexity in an interview

  1. Define the range. Say whether left and right are inclusive and what elements are currently included.
  2. Name the maintained state. Specify what a sum, map, distinct counter, or deque represents—not just its data type.
  3. State the invariant. Explain what remains true after insertion and, where applicable, after shrinking.
  4. Justify each movement. Explain why the right boundary admits new data, when the left boundary advances, and why that movement does not discard a possible optimum.
  5. Analyze the actual updates. If both boundaries move only forward, each element enters once and leaves at most once. That gives O(n) total pointer movement when state updates are constant-time or suitably amortized. Account separately for the data structure and operations used; the pattern by itself does not guarantee a bound.

For sliding-window maximum, make the deque argument explicit: every index is appended once and removed at most once, so the total deque work is linear rather than linear per window. Doocs LeetCode Wiki gives O(n) time and O(k) space for that specific method: its Sliding Window Maximum explanation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.