Lesson 18 · Core algorithms

Fixed Size Sliding Window

Every window of width k shares k − 1 values with the one before it. Keep a summary of the window and change it by one value in and one value out, instead of reading all k values again.

Fixed Size Sliding Window concept diagramThe values 4, −2, 6, 3, −8, 1, 9, 5 drawn six times, one row per window of three. Each row moves the window one place right: the value entering is green and the value that just left is red. On the right the window sums are 8, 7, 1, −4, 2 and 15, each computed from the previous one by adding the new value and subtracting the old one. The last window, 1, 9, 5, has the largest sum.k = 3 · each window = previous + entering − leaving4-263-81954 + (−2) + 6 =84-263-81958 + 3 − 4 =74-263-81957 + (-8) − (-2) =14-263-81951 + 1 − 6 =-44-263-8195-4 + 9 − 3 =24-263-81952 + 5 − (-8) =15best 15
1

What Stays the Same Between Windows

  1. Build the first window from a[0] to a[k − 1].
  2. For i from k to n − 1: add a[i], remove a[i − k].
  3. After each move the window is a[i − k + 1 .. i]; record its answer.

Take the values 4, −2, 6, 3, −8, 1, 9, 5 and look at every run of three in a row: each one is a sliding window of size k, with k = 3. There are n − k + 1 = 6 of them. The first is 4, −2, 6; the second is −2, 6, 3. The two share −2 and 6. Only the 4 left and only the 3 arrived.

A fixed size sliding window uses that overlap. Keep one running summary of the current window, such as its sum. To move right, add the value that enters and remove the value that leaves. Each move costs O(1), so all windows together cost O(n), instead of O(n·k) for adding up every window from scratch.

  • Window count: n − k + 1
  • Each value enters once and leaves once
2

Maximum Sum Subarray of Size k

The classic exercise asks for the largest sum of k consecutive values. On the values above with k = 3 the sums run 8, 7, 1, −4, 2, 15. Each one comes from the last: 8 + 3 − 4 = 7, then 7 + (−8) − (−2) = 1, and so on. The best is 15, from 1, 9, 5.

The maximum sum subarray of size k takes 3 additions for the first window and 2 operations for each of the other five, 13 in all, against 18 for summing every window. The gap grows with k: at k = 1,000 a fresh sum costs 1,000 additions per window while the slide still costs 2.

The same skeleton handles averages (divide the best sum by k at the end) and counting tasks: the number of vowels in every substring of length k, or the letter counts used to spot an anagram of a pattern in a longer string.

  • Average of each window: the sum divided by k, no extra pass
  • Counts: a frequency table, +1 for the entering value, −1 for the leaving one
3

First Negative in Every Window of Size k

Some questions ask about a particular value inside each window, not a total. For the first negative in every window of size k, keep a queue of the indexes of negative values seen so far. When a value enters and is negative, push its index on the back. When the front index has slid out of the window, pop it. The front of the queue is the answer, or 0 if the queue is empty.

On the example the answers are −2, −2, −8, −8, −8, 0. The last window, 1, 9, 5, holds no negative, and the queue is empty by then because −8 at index 4 left when the window moved past it.

  • Queue of indexes, not values, so you can tell when one has left
  • Each index is pushed once and popped at most once: O(n) total
Key reference

Terms, operations, and practical uses

Key terms

  • WindowThe k consecutive values currently in view, a[i − k + 1 .. i].
  • Entering / leaving valuea[i] joins and a[i − k] drops out on each move.
  • Monotonic dequeIndexes kept in decreasing value order, so the front is the window maximum.
Implementation

Code in Python, C++ and Java

from collections import deque


def max_window_sum(a, k):
    if k > len(a):
        return None
    window = sum(a[:k])
    best, best_start = window, 0
    for i in range(k, len(a)):
        window += a[i] - a[i - k]
        if window > best:
            best, best_start = window, i - k + 1
    return best, best_start


def first_negative(a, k):
    negatives, out = deque(), []
    for i, v in enumerate(a):
        if v < 0:
            negatives.append(i)
        if negatives and negatives[0] <= i - k:
            negatives.popleft()
        if i >= k - 1:
            out.append(a[negatives[0]] if negatives else 0)
    return out


def window_max(a, k):
    dq, out = deque(), []
    for i, v in enumerate(a):
        while dq and a[dq[-1]] <= v:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(a[dq[0]])
    return out


a = [4, -2, 6, 3, -8, 1, 9, 5]
k = 3
best, start = max_window_sum(a, k)
print("best sum", best, "window", a[start:start + k])
print("first negative", first_negative(a, k))
print("window max", window_max(a, k))
print("k too big:", max_window_sum(a, 9))
#include <deque>
#include <iostream>
#include <vector>
using namespace std;

bool maxWindowSum(const vector<int>& a, int k, int& best, int& bestStart) {
    if (k > (int)a.size()) return false;
    int window = 0;
    for (int i = 0; i < k; i++) window += a[i];
    best = window;
    bestStart = 0;
    for (int i = k; i < (int)a.size(); i++) {
        window += a[i] - a[i - k];
        if (window > best) {
            best = window;
            bestStart = i - k + 1;
        }
    }
    return true;
}

vector<int> firstNegative(const vector<int>& a, int k) {
    deque<int> negatives;
    vector<int> out;
    for (int i = 0; i < (int)a.size(); i++) {
        if (a[i] < 0) negatives.push_back(i);
        if (!negatives.empty() && negatives.front() <= i - k) negatives.pop_front();
        if (i >= k - 1) out.push_back(negatives.empty() ? 0 : a[negatives.front()]);
    }
    return out;
}

vector<int> windowMax(const vector<int>& a, int k) {
    deque<int> dq;
    vector<int> out;
    for (int i = 0; i < (int)a.size(); i++) {
        while (!dq.empty() && a[dq.back()] <= a[i]) dq.pop_back();
        dq.push_back(i);
        if (dq.front() <= i - k) dq.pop_front();
        if (i >= k - 1) out.push_back(a[dq.front()]);
    }
    return out;
}

void print(const char* name, const vector<int>& v) {
    cout << name << " [";
    for (size_t i = 0; i < v.size(); i++) cout << (i ? ", " : "") << v[i];
    cout << "]\n";
}

int main() {
    vector<int> a = {4, -2, 6, 3, -8, 1, 9, 5};
    int k = 3, best, start;
    maxWindowSum(a, k, best, start);
    cout << "best sum " << best << " window [" << a[start] << ", " << a[start + 1] << ", " << a[start + 2] << "]\n";
    print("first negative", firstNegative(a, k));
    print("window max", windowMax(a, k));
    cout << "k too big: " << (maxWindowSum(a, 9, best, start) ? "found" : "None") << "\n";
}
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Main {
    static int[] maxWindowSum(int[] a, int k) {
        if (k > a.length) return null;
        int window = 0;
        for (int i = 0; i < k; i++) window += a[i];
        int best = window, bestStart = 0;
        for (int i = k; i < a.length; i++) {
            window += a[i] - a[i - k];
            if (window > best) {
                best = window;
                bestStart = i - k + 1;
            }
        }
        return new int[] {best, bestStart};
    }

    static List<Integer> firstNegative(int[] a, int k) {
        Deque<Integer> negatives = new ArrayDeque<>();
        List<Integer> out = new ArrayList<>();
        for (int i = 0; i < a.length; i++) {
            if (a[i] < 0) negatives.addLast(i);
            if (!negatives.isEmpty() && negatives.peekFirst() <= i - k) negatives.pollFirst();
            if (i >= k - 1) out.add(negatives.isEmpty() ? 0 : a[negatives.peekFirst()]);
        }
        return out;
    }

    static List<Integer> windowMax(int[] a, int k) {
        Deque<Integer> dq = new ArrayDeque<>();
        List<Integer> out = new ArrayList<>();
        for (int i = 0; i < a.length; i++) {
            while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast();
            dq.addLast(i);
            if (dq.peekFirst() <= i - k) dq.pollFirst();
            if (i >= k - 1) out.add(a[dq.peekFirst()]);
        }
        return out;
    }

    public static void main(String[] args) {
        int[] a = {4, -2, 6, 3, -8, 1, 9, 5};
        int k = 3;
        int[] r = maxWindowSum(a, k);
        System.out.println("best sum " + r[0] + " window [" + a[r[1]] + ", " + a[r[1] + 1] + ", " + a[r[1] + 2] + "]");
        System.out.println("first negative " + firstNegative(a, k));
        System.out.println("window max " + windowMax(a, k));
        System.out.println("k too big: " + (maxWindowSum(a, 9) == null ? "None" : "found"));
    }
}
Watch it run

Step through it

Running on [4, -2, 6, 3, -8, 1, 9, 5] · k = 3

k = 3 · find the largest window sumwindows: 640-216233-84159657summing each window from scratch: 6 × 3 = 18 additionsneighbouring windows overlap in k − 1 = 2 values
Step 1

Six windows of three

Eight values and a window of k = 3 give n − k + 1 = 6 windows. Adding up each one from scratch costs 3 additions per window, 18 in all. Neighbouring windows share two values, so most of that work repeats.

Output
1 / 12
4

Window Maximum Needs a Deque

A sum can lose a value by subtraction. A maximum cannot. The window 6, 3, −8 has maximum 6; when 6 leaves, nothing in the old summary says the new maximum is 3. Rescanning the window brings back O(n·k).

The fix keeps a deque of indexes whose values decrease from front to back. A new value first removes every smaller value from the back, because those can never be a maximum again while the new value is in the window. The front is dropped once it leaves the window, and it is always the current maximum. For the example the window maxima are 6, 6, 6, 3, 9, 9. The full treatment is in monotonic queues and the problem Sliding Window Maximum.

  • Sum, count, XOR: undo by subtraction
  • Max, min: keep a monotonic deque
  • Median: two heaps with lazy deletion, O(log k) per move
5

Edge Cases and Off-by-One Errors

If k is larger than n there is no window at all; return early, before the first window reads past the end. If k equals n there is exactly one window, the whole array. If k is 1 every value is its own window.

Most bugs are in the index that leaves. The window ending at i starts at i − k + 1, so the value that just left is a[i − k], not a[i − k + 1]. Writing the first window in its own loop, then sliding from i = k, keeps the two phases from mixing.

  • k > n: no windows · k = n: one window · k = 1: n windows
  • Leaving index is i − k; the window start is i − k + 1
6

Where Fixed Windows Appear

The width is given whenever the problem names it: "every substring of length k", "the last k readings", "k consecutive days". Practice on Maximum Average Subarray, Maximum Number of Vowels in a Substring, Find All Anagrams, Permutation in String and Maximum Points You Can Obtain from Cards, where the cards left in the middle form a fixed window of n − k.

When the width is not given and grows or shrinks to meet a condition, the window is variable size; that pattern, and how to tell the two apart, is in sliding window. For range sums asked many times over different widths, prefix sums fit better.

  • Given width: fixed window · width set by a condition: variable window
  • Many queries of different widths: prefix sums