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.
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.
| Goal | Boundary rule | State |
|---|---|---|
| Fixed-length aggregate | Add right; remove the element that falls outside length K. | Sum, counts, or another removable summary. |
| Longest range under a constraint | Shrink while invalid; measure after repair. | Enough information to test validity. |
| Shortest range covering requirements | While valid, record and shrink until coverage breaks. | Required multiplicities and missing count. |
| Maximum in each fixed window | Expire 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
- Before adding a character, the current window is unique. Only the incoming character can violate that invariant.
- Remove characters from the left until the incoming character's count is one. Update the same counts used for validity.
- 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.
| Right | After adding | Removed | Valid window | Best |
|---|---|---|---|---|
| 0: a | a | none | a | 1 |
| 1: b | ab | none | ab | 2 |
| 2: c | abc | none | abc | 3 |
| 3: b | abcb (invalid) | a, then the earlier b | cb | 3 |
| 4: a | cba | none | cba | 3 |
| 5: d | cbad | none | cbad | 4 |
| 6: e | cbade | none | cbade | 5 |
Step-by-Step: Longest unique substring: abcbade
- 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
- Why can left move only forward in your chosen problem?
- How does measurement timing change between longest-unique and minimum-covering windows?
- 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.
- 1.Longest Substring Without Repeating CharactersRepair duplicate counts, then measure the longest valid range.Medium
- 2.Minimum Window SubstringTrack target multiplicities and shrink while every requirement remains covered.Hard
- 3.Sliding Window Maximum - Analytics WindowsSeparate expiration at the front from domination removal at the back of a deque.Hard