Sliding Window

How a sliding window answers questions about runs of neighbouring items in one pass, the fixed and variable-size versions, and what interviewers ask.

14 minLesson 5 of 6
On this page
  1. How a window moves
  2. Fixed-size window
  3. Variable-size window
  4. Complexity
  5. When a sliding window does not apply
  6. Pitfalls
  7. In the interview
  8. What to practise next

A sliding window is a range of neighbouring items in an array or string, together with a summary of what is inside it, such as a sum, a count or a set of values. When the window moves one step, you update the summary by adding the item that entered and removing the item that left, instead of recomputing it from every item in the range. It is used for questions about the best, longest or shortest run of consecutive items, and it turns an O(n · k) or O(n²) search into a single O(n) pass.

Without it, you would look at every possible run and add it up from scratch. Two neighbouring runs share almost all of their items, so most of that work is repeated.

How a window moves

Keep two indexes, left and right, for the first and last item inside the window. Moving right forward lets one item in, and moving left forward pushes one item out. After each move you adjust the summary for that one item only. If the window holds the items 4, 2, 7 with a sum of 13, then sliding one step to the right gives 13 − 4 + 1 = 10 for the items 2, 7, 1, because only the 4 left and only the 1 entered.

4 2 7 1 8 3 5 leaves enters 13 − 4 + 1 = 10
When the window slides one step, the 4 leaves and the 1 enters, and the 2 and the 7 in the middle are not added again.

There are two versions of the technique. In the fixed-size version, the window always holds exactly k items. In the variable-size version, the size changes, and the two indexes move independently according to a rule that the window must obey.

Fixed-size window

Use this version when the problem gives you the window size k, for example "the best total over any 3 days in a row". Add up the first k items once. After that, each step adds the new item on the right and subtracts the item that is k places behind it. The trace below finds the best 3-day total in a week of step counts.

Best 3 days in a rowUse the arrows or ← → keys
sum = steps[0] + ... + steps[k - 1]best = sumfor right from k to n - 1:  sum += steps[right] - steps[right - k]  best = max(best, sum)
  1. steps
    04
    12
    27
    31
    48
    53
    65
    k
    3
    sum
    13
    best
    13

    1The first three days add up to 4 + 2 + 7 = 13, so 13 is the best total so far.

  2. steps
    04
    12
    27
    31right
    48
    53
    65
    k
    3
    sum
    10
    best
    13

    2The 1 enters and the 4 leaves, so the sum becomes 13 + 1 − 4 = 10.

  3. steps
    04
    12
    27
    31
    48right
    53
    65
    k
    3
    sum
    16
    best
    16

    3The 8 enters and the 2 leaves, so the sum becomes 16, which is a new best.

  4. steps
    04
    12
    27
    31
    48
    53right
    65
    k
    3
    sum
    12
    best
    16

    4The 3 enters and the 7 leaves, so the sum becomes 12.

  5. steps
    04
    12
    27
    31
    48
    53
    65right
    k
    3
    sum
    16
    best
    16

    5The 5 enters and the 1 leaves, so the sum is 16 again. It ties the best, so best stays 16.

  6. steps
    04
    12
    27
    31
    48
    53
    65
    best
    16
    windows checked
    5

    6The best 3-day total is 16, first reached on the days holding 7, 1 and 8.

1 / 6
// Largest sum of k neighbouring items. Assumes 1 <= k <= nums.length.
function bestWindowSum(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]; // one in, one out
    best = Math.max(best, sum);
  }
  return best;
}
 
bestWindowSum([4, 2, 7, 1, 8, 3, 5], 3); // 16
# Largest sum of k neighbouring items. Assumes 1 <= k <= len(nums).
def best_window_sum(nums, k):
    total = sum(nums[:k])
    best = total
    for right in range(k, len(nums)):
        total += nums[right] - nums[right - k]  # one in, one out
        best = max(best, total)
    return best
 
best_window_sum([4, 2, 7, 1, 8, 3, 5], 3)  # 16

Variable-size window

When the size is not given, the problem asks for the longest or shortest run that satisfies a rule. The right edge moves forward once per item. Whenever the window breaks the rule, the left edge moves forward, removing items, until the rule holds again. This is the same-direction pattern from Two Pointers, with a summary of the window kept alongside the two indexes.

Longest window that satisfies a rule

For each new item at right, first move left forward until adding the item would no longer break the rule. Then add the item and record the window length if it is the best so far. The next example finds the longest run of letters in "streets" with no repeated letter. The summary is a set of the letters in the window, so the question "is this letter already inside?" takes O(1).

Longest run with no repeated letterUse the arrows or ← → keys
for right from 0 to n - 1:  while s[right] is in window:    remove s[left] from window; left += 1  add s[right] to window  best = max(best, right - left + 1)
  1. s
    0sleft right
    1t
    2r
    3e
    4e
    5t
    6s
    window
    {s}
    best
    1

    1The first s enters the window, which now has length 1.

  2. s
    0sleft
    1tright
    2r
    3e
    4e
    5t
    6s
    window
    {s, t}
    best
    2

    2The t enters, and the length is 2.

  3. s
    0sleft
    1t
    2rright
    3e
    4e
    5t
    6s
    window
    {s, t, r}
    best
    3

    3The r enters, and the length is 3.

  4. s
    0sleft
    1t
    2r
    3eright
    4e
    5t
    6s
    window
    {s, t, r, e}
    best
    4

    4The first e enters, and the window "stre" has length 4.

  5. s
    0s
    1tleft
    2r
    3e
    4eright
    5t
    6s
    window
    {t, r, e}
    best
    4

    5The second e is already in the window, so left moves forward until the old e is gone. The first removal is the s.

  6. s
    0s
    1t
    2rleft
    3e
    4eright
    5t
    6s
    window
    {r, e}
    best
    4

    6The window still contains an e, so the t is removed as well.

  7. s
    0s
    1t
    2r
    3eleft
    4eright
    5t
    6s
    window
    {e}
    best
    4

    7The window still contains an e, so the r is removed as well.

  8. s
    0s
    1t
    2r
    3e
    4eleft right
    5t
    6s
    window
    {}
    best
    4

    8Removing the old e leaves the window empty, so the new e can be added.

  9. s
    0s
    1t
    2r
    3e
    4eleft right
    5t
    6s
    window
    {e}
    best
    4

    9The new e enters. The window has length 1, and best stays 4.

  10. s
    0s
    1t
    2r
    3e
    4eleft
    5tright
    6s
    window
    {e, t}
    best
    4

    10The t enters. The earlier t already left the window, so there is no clash, and the length is 2.

  11. s
    0s
    1t
    2r
    3e
    4eleft
    5t
    6sright
    window
    {e, t, s}
    best
    4

    11The last s enters, and the window "ets" has length 3.

  12. s
    0s
    1t
    2r
    3e
    4e
    5t
    6s
    best
    4
    pointer moves
    11

    12The longest run without a repeat is "stre", with length 4.

1 / 12
function longestNoRepeat(s) {
  const inWindow = new Set();
  let left = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    while (inWindow.has(s[right])) { // shrink until the rule holds
      inWindow.delete(s[left]);
      left++;
    }
    inWindow.add(s[right]);
    best = Math.max(best, right - left + 1);
  }
  return best;
}
 
longestNoRepeat("streets"); // 4
def longest_no_repeat(s):
    in_window = set()
    left = 0
    best = 0
    for right in range(len(s)):
        while s[right] in in_window:  # shrink until the rule holds
            in_window.remove(s[left])
            left += 1
        in_window.add(s[right])
        best = max(best, right - left + 1)
    return best
 
longest_no_repeat("streets")  # 4

Shortest window that reaches a goal

For "the shortest run whose sum is at least a target", the roles are reversed. The right edge grows the window until the goal is reached. At that point you record the length, and then you shrink from the left for as long as the goal still holds, recording a shorter length each time. For the array [2, 3, 1, 2, 4, 3] and the target 7, the answer is 2, from the run 4, 3. This version requires every number to be positive, for the reason given in the section on when a sliding window does not apply.

// Length of the shortest run with sum >= target, or 0 if there is none.
// Assumes every number is positive.
function shortestRunAtLeast(nums, target) {
  let sum = 0;
  let left = 0;
  let best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    sum += nums[right];
    while (sum >= target) { // shrink while the goal still holds
      best = Math.min(best, right - left + 1);
      sum -= nums[left];
      left++;
    }
  }
  return best === Infinity ? 0 : best;
}
 
shortestRunAtLeast([2, 3, 1, 2, 4, 3], 7); // 2
# Length of the shortest run with sum >= target, or 0 if there is none.
# Assumes every number is positive.
def shortest_run_at_least(nums, target):
    total = 0
    left = 0
    best = float("inf")
    for right in range(len(nums)):
        total += nums[right]
        while total >= target:  # shrink while the goal still holds
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else best
 
shortest_run_at_least([2, 3, 1, 2, 4, 3], 7)  # 2

Windows that count distinct items

Some rules cannot be checked with a set, for example "the longest run with at most two different letters". Here the summary is a map from each item to the number of times it appears in the window. When an item leaves, you decrease its count, and you delete the entry when the count reaches zero, so that the size of the map is the number of distinct items. The rest of the loop is the same as the longest-window version: grow on the right, shrink on the left while the rule is broken, and record the length.

Counting windows and windows that need a maximum

Some questions ask how many runs satisfy a rule instead of the best one. If every run that ends at right and starts at or after left is valid, as when the rule is "at most k distinct letters", then each step adds right - left + 1 to the count. A question for exactly k distinct letters is usually answered as the count for at most k minus the count for at most k − 1, because "exactly" is not a rule that stays true when the window shrinks.

When the summary must be the maximum or minimum of the window, a running sum is not enough, because the item that leaves might be the maximum. The standard answer is a double-ended queue that keeps only the indexes of items that could still become the maximum, in decreasing order of value. The front of the queue is always the current maximum, and each index enters and leaves the queue once, so the scan stays O(n).

Complexity

ApproachTimeSpaceWhy
Recompute every windowO(n · k)O(1)Each of the n windows is added up from scratch with k additions.
Fixed windowO(n)O(1)Each slide does one addition and one subtraction.
Variable-size windowO(n)O(n)left and right each move at most n times. The set or map holds at most n items, or at most the alphabet size when the items are letters.

The while loop inside the for loop looks like O(n²), but left only moves forward and never passes right, so across the whole scan it moves at most n times. Every item enters the window once and leaves at most once.

When a sliding window does not apply

The technique needs the items to be consecutive, because the window is a contiguous range. If the problem asks for a subsequence, where items may be skipped, or for any subset of items, a window cannot represent the answer.

For the variants that shrink the window while a sum is too big or too small, every number must also be non-negative. The loop relies on the sum going down when an item leaves and going up when an item enters. If negative numbers are allowed, removing an item can raise the sum and adding one can lower it, so the loop cannot tell which edge to move, and it throws away windows that would have been the answer. For negative numbers, use prefix sums, usually together with a hash map.

Pitfalls

In the interview

Look for a problem that asks about a contiguous part of an array or string: a subarray or substring that is the longest, the shortest, the largest or the smallest, or one that contains certain characters. Phrases such as "consecutive", "at most k distinct", "no repeated characters", "a sum of at least", or "of length k" point to a window. If the problem allows negative numbers and asks about sums, think of prefix sums first. If the items do not have to be consecutive, a window is the wrong tool.

State the plan before you code: say whether the window is fixed or variable, what the summary holds, when the right edge moves and what makes the left edge move.

Questions to expect:

  • "There is a loop inside a loop. Why is this O(n) and not O(n²)?" The inner loop moves left, and left never moves backward and never passes right. Over the whole scan, right moves at most n times and left moves at most n times, so the total work is at most 2n steps.
  • "What is the space complexity?" A fixed window with a running sum uses O(1) space. A variable window that keeps a set or a map uses space for the distinct items in the window, which is O(n) in general and O(1) when the alphabet is fixed, for example 26 lowercase letters.
  • "Would this still work if the array contained negative numbers?" Not for sum-based windows. The window logic assumes that removing an item lowers the sum, which is false when an item can be negative. You would compute prefix sums and look up earlier prefix values in a hash map, which also runs in O(n).
  • "How would you find the longest run with at most k distinct characters?" Keep a map from character to count for the window. Add the new character on the right, and while the map has more than k keys, decrease the count of the character at left, delete the key if its count reaches zero, and move left forward. Record the length after the loop.
  • "Why a set for no repeated characters, and could you do it faster?" A set gives O(1) membership checks. You can also store the last index of each character in a map and, on a repeat, move left directly to one past that index, which avoids removing characters one at a time. You must take the larger of the new value and the current left, because the earlier occurrence may already be outside the window. The complexity stays O(n), but the left edge makes fewer moves.
Quick check

The values are [5, 1, 3, 6, 2] and the window size is 3. The first window [5, 1, 3] sums to 9. What is the sum after one slide?

The variable-size version has a while loop inside a for loop. What is its time complexity on a string of length n?

Which task is a poor fit for growing the window on the right and shrinking it on the left while the sum is too big?

In the shortest-run-with-sum-at-least-target code, why is the length recorded inside the while loop?

What to practise next

When you need the sums of many different ranges, in any order, or the numbers can be negative, read Prefix Sums, which answers each range in O(1) after one pass. For the two-index movement that the variable-size window builds on, see Two Pointers.