Workspace / Learning hub
Learning hubDSA ROADMAP · 01 / 30
LESSON 1 · SLIDING WINDOW

Keep the useful part in view.

Learn how two pointers turn repeated range calculations into one efficient pass.

THE IDEAA window is a contiguous slice that moves through your data.

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.

FIXED SIZE

The window length is given, such as the largest sum among all groups of 4 consecutive values.

VARIABLE SIZE

Grow and shrink the window to meet a rule, such as the shortest range whose sum reaches a target.

A CLOSER EXPLANATION

The window is not a new data structure; it is the range between two indices. Maintain a small summary such as a sum or character count as the boundaries move. Each element usually enters once and leaves once, so a full scan can replace checking every possible range.

WATCH THE WINDOW MOVE

Find a short range with sum at least 8

1 / 6
WINDOW SUM2
SHORTEST LENGTH—

Start with the first value. The window sum is below the target, so expand right.

A simple way to reason about it

  1. Expand: move right and include the new value.
  2. Check: does the current window satisfy the condition?
  3. Shrink: while it still qualifies, move left and 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.

NOW YOU TRY

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.

EXAMPLEtarget = 8
numbers = [2, 3, 1, 2, 4, 3]
Expected output: 3

Before 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.

CONNECT IT TO REAL LIFE

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.