Sliding Window — Algorithms

Sliding window calculates something, like a sum, from a window: a group of k numbers that sit side by side in an array. Then the window slides one step at a…

If you already know [2, 1, 5] adds up to 8, what does [1, 5, 1] add up to? No need to add three numbers again from the start: 8 - 2 + 1 = 7. The 1 and 5 in the middle haven't changed, so you just drop the number leaving and add the number coming in.

This trick is called sliding window. Sliding window calculates something from a group of numbers that sit side by side in an array, for example the sum of 3 numbers in a row. Then that group slides one step at a time. The group is called the window, and how many numbers it holds is called k. Think of a train window: each time the train moves forward, one view comes in on the right and one leaves on the left. The train window is the group of numbers, and the views passing by are the numbers in the array.

Slide, don't recompute

The task: find the biggest sum of k = 3 numbers that sit side by side in [2, 1, 5, 1, 3, 2, 8, 4].

Step Window Calculation Total Biggest so far
1 2, 1, 5 2 + 1 + 5 8 8
2 1, 5, 1 8 - 2 + 1 7 8
3 5, 1, 3 7 - 1 + 3 9 9
4 1, 3, 2 9 - 5 + 2 6 9
5 3, 2, 8 6 - 1 + 8 13 13
6 2, 8, 4 13 - 3 + 4 14 14

Only the first window is added up in full. After that, each slide takes just two calculations: take away the number leaving on the left, add the number coming in on the right. If the array were only [2, 1, 5, 1, 3, 2], the window would stop at step 4, and the answer would be 9.

Each window is a subarray: a piece of an array whose items sit side by side. Here is the code, as a function named maxSumSubarray:

function maxSumSubarray(arr, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) {
    sum += arr[i];
  }

  let max = sum;

  for (let i = k; i < arr.length; i++) {
    sum += arr[i] - arr[i - k];
    if (sum > max) {
      max = sum;
    }
  }

  return max;
}

console.log(maxSumSubarray([2, 1, 5, 1, 3, 2, 8, 4], 3)); // 14

The two loops sit one after the other, not nested (a loop inside a loop). Both use the k parameter, so the function works for any window size (k).

Why it's faster

The plain way, recomputing, adds up k numbers again at every window position. For n numbers, the work is about n × k: O(n × k). When k is about half of n, that is already O(n²), like nested loops.

Sliding window needs only O(n). That means: twice the data, roughly twice the time. The reason is that each number is handled at most twice: once when it enters the window, once when it leaves. In the Lab, one operation is one number added or taken away. With 8 numbers and k = 3, sliding takes 13 operations, while recomputing takes 18. The bigger k gets, up to about half of n, the wider that gap.

Use sliding window when the task is about numbers or letters that sit side by side: "the sum of 5 days in a row", "the average of the last 7 readings". If you may pick numbers from anywhere, it isn't a window problem.

⚠️ Why is the window sum wrong?

💡 A window whose size changes. Some tasks ask things like "the shortest window whose sum is at least 7". In that task the size isn't fixed. The right edge of the window moves forward to add numbers. Then the left edge moves forward to drop numbers, as long as the sum is still at least 7. Same idea: each number comes in once and goes out once.

TL;DR: Sliding window calculates something, like a sum, from a window: a group of k numbers that sit side by side in an array. Then the window slides one step at a time. Add up the first window once. After that, each slide is just sum += arr[i] - arr[i - k]: add the number coming in (arr[i]), take away the number going out (arr[i - k]). Keep the biggest sum in max, which starts from the first window's sum. For n numbers the work is O(n), not O(n × k), because each number is handled at most twice.

⚡ Slide, don't recompute

Guess first: [2, 1, 5] adds up to 8. What does [1, 5, 1] add up to, without adding three numbers again from the start?

8 - 2 + 1 = 7. The 1 and 5 in the middle haven't changed, so you just drop the number leaving and add the number coming in.

Meaning: The window is a group of k numbers that sit side by side in an array. Sliding window moves that window one step at a time. Only the first window is added up in full. After that, each slide takes just two calculations: take away the number leaving, add the number coming in.

⚡ Add the one coming in, take away the one going out

Write:

function maxSumSubarray(arr, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) {
    sum += arr[i];
  }

  let max = sum;

  for (let i = k; i < arr.length; i++) {
    sum += arr[i] - arr[i - k];
    if (sum > max) {
      max = sum;
    }
  }

  return max;
}

Meaning: maxSumSubarray finds the biggest sum of k numbers that sit side by side in arr. The first loop adds up the first window. In the second loop, arr[i] is the number coming in on the right, arr[i - k] the number leaving on the left. max starts at the first window's sum, not at 0, so it's still right when every number is negative.

⚡ Why it's faster

Meaning: Recomputing adds up k numbers again at every window position: O(n × k), where n is how many numbers there are. Sliding window is only O(n), because each number is handled at most twice, once when it enters the window and once when it leaves.

What you will learn