Lesson 17 · Core algorithms

Sliding Window Technique

A sliding window keeps a running summary of a contiguous range, a sum, a count or a frequency map, and updates it as the range's ends move instead of recomputing it. That turns O(n·k) or O(n²) scans into O(n).

Sliding Window Technique concept diagramA visual explanation of the layout and operations shown in this lesson.track one contiguous subsegment215132current window: indices 2 through 4
1

Reusing the Overlap

The sliding window technique is for questions about contiguous ranges: subarrays or substrings. Two neighbouring windows share everything except one value at each end, so after the first window there is no need to look at the whole range again. Subtract the value that leaves, add the value that enters, and the new answer is ready in O(1).

The running value is the window's summary: a sum, a count, a frequency map of characters. It works as long as the summary can be updated both when a value enters and when one leaves. A sum can, because subtraction undoes addition. A maximum cannot: when the largest value leaves, the next largest is unknown without rescanning, which is why the maximum of every window needs a monotonic queue instead of one variable.

  • It is a two pointers pattern where both pointers move in the same direction
  • Counting characters in a fixed array of 26 or 128 slots is faster than a hash map for plain text
2

Windows of a Given Width

  1. Build the first window: sum the first k values
  2. For i from k to n − 1: add a[i] and subtract a[i − k]
  3. After each move, compare the window's value with the best so far

When the width k is given, both ends move together and the loop needs no decisions. On [2, 1, 5, 1, 3, 2] with k = 3 the sums are 8, 7, 9 and 6, each new one from the last with one addition and one subtraction, so the best is 9 from [5, 1, 3]. Recomputing every window would cost k additions each, O(n·k) in total; sliding costs O(n) whatever k is.

The usual bug is at the start. A single loop that records an answer from the very first index records sums of half-built windows. For a maximum of positive numbers that is harmless by luck; for a minimum it is wrong, because a partial window looks small. Record only once i >= k − 1, or build the first window in its own loop.

3

Windows That Grow and Shrink

  1. Move right one step and add a[right] to the summary
  2. While the window breaks the condition, remove a[left] and move left one step
  3. The window is valid again: record its length if it is the best so far

When the question gives a condition instead of a width, such as the longest subarray with sum ≤ 7 or the longest substring with no repeated character, the two ends move separately. right always moves forward and adds a value; left moves only when the window has broken the condition, and stops as soon as it is fixed.

The code looks quadratic because of the inner while, but it is O(n). left never moves backwards and can move at most n times over the whole run, so the inner loop does at most n steps in total. Each value enters the window once and leaves at most once.

Longest and shortest questions shrink for opposite reasons, and mixing them up is the most common mistake:

Longest window vs shortest window
QuestionShrink whileRecordExample
Longest valid windowthe window is invalidafter shrinkinglongest substring without repeating characters
Shortest valid windowthe window is still validbefore each shrinkminimum size subarray sum
Key reference

Terms, operations, and practical uses

Core vocabulary

  • WindowA contiguous sequence of elements in an array or string bounded by two indices (left and right).
  • Fixed SizeA window where the distance between the left and right pointers remains exactly K.
  • Dynamic SizeA window that grows or shrinks as needed to satisfy a particular condition.

Operations

  • ExpandIncreasing the window size by moving the right pointer and including a new element in the state.
  • ShrinkDecreasing the window size by moving the left pointer and removing its element from the state.
  • State UpdateModifying the running metric (sum, product, frequency map) in O(1) time when the window boundaries change.

Data structures

  • Hash Map / DictionaryUsed to keep track of character frequencies or counts of elements currently inside the window.
  • Frequency ArrayA fixed-size array (like int[128]) often used instead of a Hash Map for ASCII string problems to improve speed.
  • DequeA double-ended queue used in monotonic sliding window problems (like finding the maximum in every window of size K).
Implementation

Code in Python, C++ and Java

def max_sum(arr, k):
    window_sum = sum(arr[:k])
    max_val = window_sum
    for i in range(k, len(arr)):
        window_sum += arr[i] - arr[i-k]
        max_val = max(max_val, window_sum)
    return max_val
print(max_sum([2, 1, 5, 1, 3, 2], 3), '(from [5, 1, 3])')
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int maxSum(vector<int>& arr, int k) {
    int windowSum = 0;
    for (int i = 0; i < k; i++) windowSum += arr[i];
    int maxVal = windowSum;
    for (int i = k; i < arr.size(); i++) {
        windowSum += arr[i] - arr[i - k];
        maxVal = max(maxVal, windowSum);
    }
    return maxVal;
}

int main() {
    vector<int> arr = {2, 1, 5, 1, 3, 2};
    cout << maxSum(arr, 3) << " (from [5, 1, 3])\n";
}
public class Main {
    static int maxSum(int[] arr, int k) {
        int windowSum = 0;
        for (int i = 0; i < k; i++) windowSum += arr[i];
        int maxVal = windowSum;
        for (int i = k; i < arr.length; i++) {
            windowSum += arr[i] - arr[i - k];
            maxVal = Math.max(maxVal, windowSum);
        }
        return maxVal;
    }

    public static void main(String[] args) {
        int[] arr = {2, 1, 5, 1, 3, 2};
        System.out.println(maxSum(arr, 3) + " (from [5, 1, 3])");
    }
}
Watch it run

Step through it

Running on [2, 1, 5, 1, 3, 2], k = 3

fixed window, k = 3: sum a[0..2]array201152133425sum 8built once: k additionswindowwindow[2, 1, 5]sum8best8operations3 adds
Step 1

Build the first window

The first window of size 3 has to be summed in full: 2 + 1 + 5 = 8. That is the only time the loop adds k values; every later window is derived from the one before it.

Output
1 / 12
4

When the Sliding Window Fails

A variable window relies on one rule: adding a value can only push the summary one way, and removing one can only pull it back. With non-negative numbers a sum only grows as the window grows, so shrinking is the right fix for a sum that is too big.

Negative numbers break that rule. Take the longest subarray of [5, −4, 1] with sum ≤ 2. The whole array sums to 2, so the answer is 3. The window sees 5 first, decides it is too big and throws it away, never learning that the −4 after it would have balanced it, and reports 2. For sums with negatives, use prefix sums with a hash map or a sorted structure instead: see subarray sum equals k.

Subsequences are not windows. A subsequence may skip values, so there is no contiguous range to slide; those questions are usually dynamic programming.

  • Check the input constraints for negative values before reaching for a window
  • "Exactly k" counts are rarely a direct window; compute atMost(k) − atMost(k − 1), as in subarrays with k different integers
5

Recognising a Sliding Window Problem

Three signs together point to a window: the question is about a contiguous range (subarray or substring), it asks for a longest, shortest, maximum or count over those ranges, and the obvious solution is two nested loops over every start and end. If the values are non-negative or the condition is a count of distinct items, the sliding window algorithm almost always applies.

The real design choice is the summary. A running sum or count handles arithmetic limits. A frequency map handles anagram, distinct-character and "contains all of" questions; pair it with one integer that says how many characters currently meet their target, so checking validity stays O(1) and the whole algorithm stays O(n).

  • Fixed width given: fixed window. Condition given: variable window
  • Values may be negative: prefix sums, not a window