DSA Trainer
← Foundations

Foundations · Unit 4

Sliding Window

You are asked for the highest-scoring stretch of five games in a row, or the longest run of distinct characters, or the smallest slice of an array that adds up to at least some number. All three are about a contiguous run, a window, and the brute force is to check every possible window from scratch. That re-does an enormous amount of work, because neighboring windows overlap almost entirely.

The sliding window technique keeps a running summary of the current window and slides it one step at a time: add what enters on the right, remove what leaves on the left. Nothing gets rescanned, so a problem that looked quadratic collapses to a single linear pass. It is really the same-direction two-pointer idea, aimed specifically at contiguous subarrays and substrings.

There are two shapes. A fixed window has a set size and just slides along. A variable window grows and shrinks to find the best run under some condition. The hard part is rarely the code; it is recognizing that a problem is a window at all, and knowing when to grow versus when to shrink. That is what this unit builds.

Goal: Recognize a contiguous-subarray problem and maintain a window that grows and shrinks in one pass, instead of re-checking every subarray.
Lesson 1 of 60%

You’re not signed in. Your progress here won’t be saved.

The pain: recomputing every window

Find the largest sum of any four numbers in a row in [2, 1, 5, 1, 3, 2]. The obvious approach sums positions 0 to 3, then sums positions 1 to 4, then 2 to 5, re-adding four numbers each time.

For a window of size k across n elements, that is about n times k additions. The waste is the overlap: sliding from one window to the next changes only two elements, the one that leaves and the one that joins, yet you re-added everything in between.

You compute the sum of every length-k window in an n-element array by re-adding all k elements each time. Roughly what does that cost?

Premium practice

The drills and graded test are premium

The lessons above are free. The interactive practice that turns recognizing the pattern into recalling it on a blank page unlocks with premium:

  • 3 applied drills: train spotting when the concept applies
  • A 5-question graded test to clear the unit
  • The full guided problem ladder with faded hints, plus the cold-read capstone
Unlock everything →

From $6/month. Cancel anytime.