Skip to main content

Sliding Window: Maintain a Contiguous Range

A sliding window is a contiguous range whose summary can be updated when either endpoint moves. The hard part is not maintaining two indices: it is proving that a discarded left boundary never needs to return. Define validity and the direction of improvement before choosing when to shrink.

FrontendInterviews.dev Updated

Recognize the Pattern

  • A substring or subarray must be contiguous; arbitrary subsequences are a different problem.
  • Adding and removing one item updates counts or a sum without rescanning the whole range.
  • The constraint permits forward-only repair. Negative sums can destroy the monotonicity that a positive-sum window relies on.

Core Invariant

The counts summarize exactly [left, right]. After duplicate repair, every character in the current window occurs once.

Important Boundary

Longest-valid windows measure after repair; shortest-covering windows measure before removing required coverage. Sum-based shrinking needs a monotonicity proof.

For abcbade, the window grows to abc, becomes invalid at abcb, shrinks twice to cb, and grows to cbade of length 5.
For abcbade, the repeated b requires removing a and the earlier b. The final unique window cbade has length 5. L and R mark the current boundaries.

Choose what makes the window useful

Do not use a generic shrink condition for every problem. Minimum Window Substring needs repeated letters in the target, not merely membership in a set. If t is AABC, two As are necessary. A window maximum cannot subtract the old maximum; it needs candidates that survive expiration.

GoalBoundary ruleState
Fixed-length aggregateAdd right; remove the element that falls outside length K.Sum, counts, or another removable summary.
Longest range under a constraintShrink while invalid; measure after repair.Enough information to test validity.
Shortest range covering requirementsWhile valid, record and shrink until coverage breaks.Required multiplicities and missing count.
Maximum in each fixed windowExpire old indices and discard dominated candidates.A monotonic deque, not only a running maximum.

Repair duplicates before measuring

Template Assumptions

  • String input indexed as UTF-16 code units; the result is a length, not the actual substring.
  • Map counts describe the current window; zero-count entries are removed.
JavaScript Template
function longestUniqueLength(text) {
  const counts = new Map();
  let left = 0, best = 0;
  for (let right = 0; right < text.length; right++) {
    const char = text[right];
    counts.set(char, (counts.get(char) ?? 0) + 1);
    while (counts.get(char) > 1) {
      const removed = text[left++];
      counts.set(removed, counts.get(removed) - 1);
      if (counts.get(removed) === 0) counts.delete(removed);
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}
  1. Before adding a character, the current window is unique. Only the incoming character can violate that invariant.
  2. Remove characters from the left until the incoming character's count is one. Update the same counts used for validity.
  3. Measure the repaired window. An earlier start still containing the duplicate cannot produce a valid range ending here or later without removing that duplicate.

Trace abcbade: grow, repair, then grow again

The answer is 5. At right = 3, keep right fixed and move left twice: abcb becomes bcb, then cb. Neither invalid length 4 nor invalid length 3 updates best. The later a is allowed because the earlier a has already left the window.

For a shortest-covering window, reverse the measurement timing: measure while coverage is still valid, then remove the left character and check again.

RightAfter addingRemovedValid windowBest
0: aanonea1
1: babnoneab2
2: cabcnoneabc3
3: babcb (invalid)a, then the earlier bcb3
4: acbanonecba3
5: dcbadnonecbad4
6: ecbadenonecbade5

Step-by-Step: Longest unique substring: abcbade

Step 1 / 10
a0Lb1c2b3a4d5e6
Boundaries
left = 0, right = -1
Current window
""; length = 0; valid
Counts
empty
Best valid length
0

Start with an empty window

No characters have entered. left is 0, right is -1, and the best valid length is 0.

Count moves, not nested loops

  • Each character enters once and leaves at most once: O(N) endpoint moves despite the nested while loop. Map operations are conventionally analyzed as expected constant time.
  • Counts need O(D) space for the distinct characters currently represented. Delete zero entries to avoid retaining historical characters.
  • The template indexes UTF-16 code units. For Unicode code points, convert to Array.from(text); grapheme clusters need a segmentation policy. Conversion adds O(N) storage.
  • For general signed subarray sums, consider prefix sums and a hash map for exact sums, or a prefix-sum deque for some inequality problems. Do not transplant the positive-sum proof.

Mistakes and Counterexamples

Track target letters without their multiplicities.

Counterexample: For target AABC, a window ABC contains every distinct target letter but lacks the second A.

Correction: Compare required counts with current counts; a set cannot represent repeated requirements.

Use sum-based shrinking without checking signs.

Counterexample: For [3, -2] with sum limit 2, discarding 3 immediately misses the valid length-two range with sum 1.

Correction: Prove monotonic repair under the input constraints; signed values may require prefix-sum techniques.

Last-Minute Recap

  • Define contiguity, validity, and measurement timing.
  • Both boundaries move forward only after an elimination proof.
  • Use counts for multiplicities and a deque when extrema expire.
  • Include preprocessing and state storage in complexity.

Explain It in an Interview

  1. Why can left move only forward in your chosen problem?
  2. How does measurement timing change between longest-unique and minimum-covering windows?
  3. What state is needed when a target has repeated letters?

Ready to Apply This Pattern?

Before coding, explain why this pattern fits and what must stay true at each step. Start with an easier problem, then test that reasoning on a harder variation.

Ordered from Easy to Hard. Premium access requirements still apply.

References