Skip to content
Algorithms for Beginners

Patterns / Pattern 3 of 5

Sliding window

Keep a stretch of the list and slide it along instead of starting over.

The 30-second version

You're on a train, looking through a window that shows three houses at a time. As the train moves, one new house appears on the right and one disappears on the left. You never look at the whole street again: only what came in and what went out.

Sliding window, in three steps:

  1. Look at a stretch of items next to each other (the window).
  2. Slide it: add the new item on the right, drop the old one on the left.
  3. Keep note of the best window you've seen.

Think of it when a problem says:

  • “in a row”
  • “next to each other”
  • “the longest stretch”
  • “the shortest part that…”

That’s the whole idea. The rest of this page shows it working, step by step.

Spot it when: You want the best stretch of items next to each other.
In one line: Add the one coming in, drop the one going out.

Words on this page, in plain English (16)Open if any word is new to you
Variable
A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Index (position)
Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
Length
How many items a list (or letters a string) has. The last position is always length - 1.
Loop
Code that repeats. A for loop repeats once per item or a set number of times; a while loop repeats as long as something stays true.
Function
A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
Return
How a function hands back its answer. As soon as return runs, the function stops.
console.log
Prints something so you can see it. The easiest way to find out what your code is really doing.
Map
A lookup table: it stores pairs of a key and a value, and finds any key instantly. Like a coat check: hand over a ticket, get your coat straight back.
Set
A collection that only remembers which things it has seen, with no repeats. Like a guest list: a name is either on it or not.
Hash, hashing
A quick calculation that turns a key into a shelf number, so a Map can jump straight to it instead of searching.
Pattern
A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
Brute force (the slow way)
Trying every possibility, one by one. It's usually easy to write and correct, but slow on big inputs.
O(n): linear time
The work grows in step with the input: twice the items, twice the work. One pass.
O(n²): quadratic time
Twice the items means four times the work. Usually a loop inside a loop. Fine for 100 items, painful for 100,000.
Window
A stretch of items next to each other in a list, from a left position to a right one.

Every word, explained simply

Stretches of a list

Many problems ask about a stretch of items that sit next to each other: "the best 7 days in a row", "the longest part of this text with no repeated letter". A stretch like this is called a window: a start position, an end position, and everything in between.

The slow way looks at every possible window separately. A list of 10,000 items has about 50 million windows, and adding up each one from scratch takes even longer.

The sliding window pattern notices that neighbouring windows are almost the same. Moving a window one step right just adds one item at the right edge and drops one at the left. So instead of starting over, we update what we know about the window.

Watch it work: slide a 3-day window

temps

window sum =
12
best =
12

Add up the first 3 days: 5 + 1 + 6 = 12. That's the best so far.

Fixed-size windows

When the window always has the same size k, slide it one step at a time: add the item coming in, subtract the item going out.

Try it: sums of every 3 days in a row

const sales = [4, 2, 7, 1, 8, 3];
const k = 3;

let sum = 0;
for (let i = 0; i < k; i++) sum += sales[i]; // the first window
console.log("days 0-2:", sum);

for (let right = k; right < sales.length; right++) {
sum += sales[right]; // the new day comes in
sum -= sales[right - k]; // the oldest day leaves
console.log("days " + (right - k + 1) + "-" + right + ":", sum);
}

Press Run to see the output. You can change the code first.

Each step costs the same small amount, however big k is. That's the whole trick.

Growing and shrinking windows

Often the window's size isn't fixed: we want the longest (or shortest) window that follows some rule. Then the window grows and shrinks:

  • The right edge moves forward one step at a time, adding an item.
  • If the window breaks the rule, the left edge moves forward, removing items, until the rule holds again.
  • After each step, the window is valid, so check whether it's the best so far.
function longestValidWindow(items) {  let left = 0;  let best = 0;  // ...something that describes what's in the window (a sum, a Map of counts)...  for (let right = 0; right < items.length; right++) {    // 1. add items[right] to the window    while (/* the window breaks the rule */) {      // 2. remove items[left] from the window      left++;    }    // 3. the window from left to right is valid    best = Math.max(best, right - left + 1);  }  return best;}

A window from left to right holds right - left + 1 items. That + 1 is easy to forget: a window from 2 to 2 holds one item.

Why it's fast

There's a loop inside a loop, which looks like O(n²). But left only ever moves forward, and it can't pass right. So across the whole run, left moves at most n times in total, and right moves n times. That's O(n) overall.

Race: how much work as the input grows?

Add up every stretch from scratch O(n²)1,000,000 steps · 10 ms

Slide the window O(n)1,000 steps · instant

Times assume a fast computer doing about 100 million simple steps a second.

What goes in the window

To check the rule quickly, keep a summary of the window, updated as items come in and go out:

RuleKeep track of
Sum at least / at most somethinga running sum
No repeated itemsa Set, or a Map of counts
At most k different itemsa Map of counts; its size is the number of different items
Same letters as another worda Map of letter counts

This is where sliding window meets hashing: a Map of what's inside the window is very common.

When to use it

Reach for a sliding window when a problem asks about:

  • a stretch of items next to each other (also called a subarray or substring),
  • the longest, shortest or best such stretch,
  • every stretch of a fixed size.

If the items don't need to be next to each other, it's not a window problem.

Common mistakes

  • Rebuilding the window from scratch. If you have a loop that re-adds every item in the window at each step, you've lost the speed-up.
  • Forgetting to remove items when left moves. The summary must always describe exactly the items from left to right.
  • Measuring the window as right - left. It's right - left + 1.
  • Shrinking with if instead of while. Sometimes several items must leave before the window is valid again.

Learn it by heart

Understanding a pattern is the first half. The second is being able to write it without looking. Learn the recipe as words first, then each template in four steps. Your results go into your reviews, which bring each one back just before you’d forget it.

The recipe, out loud

  1. Grow the window by moving right one step at a time.
  2. Add the new item to what you know about the window (a sum, a Map).
  3. While the window breaks the rule, remove items[left] and move left up.
  4. The window is valid now: compare it with the best so far.

A window of fixed size

Use it for: The best total of exactly k items in a row.

Learn it by heart: A window of fixed size

Read the 10 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.

function bestSumOfK(nums, k) {  let sum = 0;  for (let i = 0; i < k; i++) sum += nums[i];  let best = sum;  for (let right = k; right < nums.length; right++) {    sum += nums[right] - nums[right - k];    best = Math.max(best, sum);  }  return best;}

Grow, then shrink until valid

Use it for: The longest (or shortest) stretch that follows a rule.

Learn it by heart: Grow, then shrink until valid

Read the 14 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.

function longestWithSumAtMost(nums, limit) {  let left = 0;  let sum = 0;  let best = 0;  for (let right = 0; right < nums.length; right++) {    sum += nums[right];    while (sum > limit) {      sum -= nums[left];      left++;    }    best = Math.max(best, right - left + 1);  }  return best;}

Practice problems

Easiest first. Each has hints and a full walkthrough.

SolvedProblemDifficulty
Best streakeasy
Longest unique stretchmedium
Shortest to targetmedium
Repaint the fencemedium
Hidden shufflemedium
Two kindsmedium

More patterns

  • Binary search

    Halve the search space with every guess.

  • Stack

    Keep the most recent unfinished thing on top, and finish it first.

  • Hashing and counting

    Remember what you have seen in a Map, so you never search for it twice.

  • Two pointers

    Walk through a list from both ends (or at two speeds) at once.

New to coding? Start with the JavaScript basics, or browse every practice problem.