Keep the useful part in view.
Learn how two pointers turn repeated range calculations into one efficient pass.
Keep a left and right boundary. Expand the right boundary to include new values; move the left boundary to remove values when the window needs to shrink.
When does this pattern help?
Look for words like contiguous, consecutive, substring, or subarray. Sliding window is especially useful when a range can be updated as its boundaries move, instead of recalculating the whole range each time.
The window length is given, such as the largest sum among all groups of 4 consecutive values.
Grow and shrink the window to meet a rule, such as the shortest range whose sum reaches a target.
Find a short range with sum at least 8
Start with the first value. The window sum is below the target, so expand right.
A simple way to reason about it
- Expand: move
rightand include the new value. - Check: does the current window satisfy the condition?
- Shrink: while it still qualifies, move
leftand update the best answer.
This sum-based shrinking approach relies on positive numbers. With negative values, removing an item can increase or decrease the sum unpredictably, so a different technique may be needed.
Minimum length subarray
Given an array of positive integers and a target, return the minimum length of a contiguous subarray whose sum is at least the target. Return 0 if no such subarray exists.
target = 8
numbers = [2, 3, 1, 2, 4, 3]Expected output: 3Before coding, explain: when do you move right, and what condition lets you move left?
Show a hint
Expand right until the sum reaches 8. Then record the length and keep moving left while the sum remains at least 8.
Sliding Window at work
A food delivery service tracks orders completed each hour. It needs the shortest consecutive block of hours with at least 20 orders. Given hourly counts [4, 3, 8, 2, 7], what is the shortest block length?
Show one possible approach
4 hours: [3, 8, 2, 7] totals exactly 20. No length-3 window reaches 20, so this is the shortest qualifying block.