Recognize the Pattern
- Sorted order lets a comparison rule eliminate an entire family of pairs.
- In-place stable compaction separates a read position from the next write position.
- A boundary's limiting value or relative pointer speed provides a proof that does not require sorted input.
Core Invariant
After measuring a container, retaining its shorter side while moving the other endpoint inward cannot improve that pair's area.
Important Boundary
Pointer roles need different proofs. Do not sort container heights, or apply sorted-pair movement to unsorted values.
Choose roles before movement
Sliding windows are a related same-direction technique for contiguous ranges, covered separately. Container heights do not need to be sorted: their elimination proof comes from the shorter side. Sorting them would destroy the original widths.
| Roles | Example | Reason to move |
|---|---|---|
| Opposite ends | Sorted pair sum | Too-small sum eliminates the current left value with all remaining right values. |
| Read and write | Move Zeroes | The written prefix already contains every kept value in original order. |
| Slow and fast | Linked List Cycle | Within a cycle, the relative offset changes by one per step. |
| Two limiting sides | Container With Most Water | Keeping the shorter side and narrowing cannot improve this pair's area. |
Move the side that cannot improve
Suppose the left height is no greater than the right height. Any container retaining that left side and moving the right endpoint inward has a smaller width and height at most the old left height. Its area cannot beat the pair just measured, so discard the left side. When heights tie, either side is safe to discard.
Template Assumptions
- Nonnegative numeric heights at original unit-spaced positions; fewer than two heights returns zero.
- Finds maximum area only, without changing the input or returning endpoint indices.
JavaScript Template
Follow the shorter side, not the taller one
| Left, right | Limiting height | Area | Move |
|---|---|---|---|
| 0,8 | 1 | 8 | left to 1 |
| 1,8 | 7 | 49 | right to 7 |
| 1,7 | 3 | 18 | right to 6 |
| 1,6 | 8 | 40 | left to 2 (tie) |
| 2,6 | 6 | 24 | left to 3 |
| 3,6 | 2 | 6 | left to 4 |
| 4,6 | 5 | 10 | left to 5 |
| 5,6 | 4 | 4 | left to 6; stop |
Step-by-Step: Container area: measure, then move the shorter side
- Left, right
- 0,8
- Width and limiting height
- 8, 1
- Current area
- 8
- Best area
- 8
Measure sides 0 and 8
Area = 1 x 8 = 8. Best is 8. Move the shorter left side. Retaining that side while narrowing the width cannot beat the pair just measured.
Preserve identity and duplicate policy
- For sorted pair sum, keep left < right so an item cannot pair with itself. Sorting original values loses original indices unless you retain index records.
- For Three Sum, sort, fix one value, then search pairs. Skip repeated anchors and repeated pair values only after accounting for a result. Its scan is O(N squared), not O(N).
- For Move Zeroes, advance write only when keeping a value; fill the remaining suffix afterward. This preserves nonzero order.
- Floyd's cycle detection needs null checks before advancing fast.next.next. It answers a linked-structure question, not a window question.
Separate preprocessing from scanning
- The container scan is O(N) time and O(1) auxiliary space, with no sorting or mutation.
- A sorted pair scan is O(N), but comparison sorting first conventionally costs O(N log N). Copies and index records require O(N) storage.
- Stable compaction and Floyd's cycle test are linear with constant auxiliary state; enumerate the extra output storage separately.
Mistakes and Counterexamples
Move the taller container side first.
Counterexample: For [1,2,4,3], discarding the right side at pair (0,3) skips the best pair (1,3), with area 4.
Correction: Eliminate the shorter side, whose fixed height cannot compensate for reduced width.
Apply sorted pair movement to unsorted data.
Counterexample: For [3,2,4] and target 6, an opposite-end scan can discard 4 before finding the valid pair 2 + 4.
Correction: Establish the ordering condition, or use a hash map when original order and indices must remain intact.
Last-Minute Recap
- Give each pointer a role.
- Prove the eliminated candidates cannot improve the answer.
- Sorted-pair, compaction, cycle, and container proofs are different.
- Include sorting, repeated scans, and output costs.
Explain It in an Interview
- Which family of candidates does your pointer move eliminate?
- Why is either move safe when container heights tie?
- How does a read/write invariant differ from opposite-end pair search?
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.Valid PalindromeCompare retained characters from opposite ends under the specified normalization rules.Easy
- 2.Move Zeroes - Array ReorderingMaintain a stable written prefix without overwriting unread nonzero values.Easy
- 3.Linked List CycleExplain why different traversal speeds meet in a cycle and guard null links.Easy
- 4.Merge Two Sorted ListsAdvance the smaller current head while preserving links to each unconsumed suffix.Easy
- 5.3SumFix one sorted anchor and deduplicate pair outputs without losing valid triples.Medium
- 6.4SumExtend fixed anchors while preserving bounds, multiplicity, and duplicate policy.Medium
- 7.Container With Most WaterProve that retaining the shorter side cannot improve the measured pair.Medium
- 8.Remove Nth Node From End of ListMaintain a fixed gap and use a sentinel to handle removal of the head uniformly.Medium
- 9.Next Lexicographical PermutationFind the descending suffix, swap the pivot with its successor, then reverse the suffix.Medium
- 10.Rotate Array - Circular ShiftUse opposite-end swaps for three reversals and normalize the rotation by array length.Medium
- 11.Longest Palindromic SubstringExpand around odd and even centers and compare candidate lengths without assuming one center type.Medium
- 12.Trapping Rain WaterUse a boundary-maximum invariant rather than reusing the container area formula.Hard