All algorithms
Searching

Sliding Window

Reuse the previous window's answer instead of recomputing it.

TimeO(n)SpaceO(1)CategorySearching

A sliding window keeps a running answer for a contiguous range. To move the window one step right you add the element entering and subtract the element leaving — the interior is never touched again, so each step is O(1) instead of O(k).

It turns 'best sum of any k consecutive elements' from O(n·k) into O(n), and the variable-size version (grow while valid, shrink while invalid) solves longest-substring and minimum-window problems the same way.

The single line `sum += a[i] - a[i - k]` is doing two things at once. AlgoLens shows the window boundaries on the array as it slides, so that line stops being a trick and becomes obvious.

The code

sliding_window.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {2, 1, 5, 1, 3, 2};
    int k = 3;
    int sum = 0, best = 0;

    for (int i = 0; i < k; i++) sum += a[i];
    best = sum;

    for (int i = k; i < (int)a.size(); i++) {
        sum += a[i] - a[i - k];
        best = max(best, sum);
    }

    cout << best << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Sliding Window

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going