M15 · Sliding Window

Sliding Window: Fixed and Variable Windows

Many questions about contiguous subarrays can be answered by sliding a window across the array and updating a running total instead of recomputing it. This lesson covers fixed windows, variable windows that grow and shrink, the non-negativity precondition that makes shrinking correct, and the amortized argument for O(n).

~40 minIntermediateC# · Python · Java · C++
Curriculum: M15 Sliding Window · 1 of 1 lessons available

You will be able to

  • Update a fixed-size window sum in O(1) per step by adding the entering value and subtracting the leaving one.
  • Run an expand/shrink window for "longest run with sum ≤ limit" and state its invariant.
  • Explain why the variable window needs non-negative values, and give a counterexample with a negative value.
  • Show that the nested shrink loop is still O(n) overall (each index enters and leaves at most once).
  • Pick 64-bit sums in C#, Java and C++ and know that Python needs none.

Helpful before this lesson

  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A window is a contiguous range [left, right] of the array, together with a summary of what is inside it: a sum, a count, a frequency table. Sliding the window one step changes it only at the edges: one value enters on the right, maybe one leaves on the left. If the summary can be updated from those two values alone, each step costs O(1) instead of re-reading the whole window.

There are two kinds:

  • Fixed size. The window always holds exactly k values; every step adds one and removes one.
  • Variable size. The window grows on the right while it is valid and shrinks from the left when it is not. It is the same-direction two-pointer pattern from the previous lesson, with a running summary attached.

Fixed window: the largest sum of k consecutive values

sum = values[0] + … + values[k-1]          # the first window
best = sum, bestStart = 0
for right in k .. n-1:
    sum += values[right] - values[right - k]   # one enters, one leaves
    if sum > best: best = sum, bestStart = right - k + 1
return (best, bestStart)

Recomputing each of the n − k + 1 windows from scratch reads (n − k + 1) · k values, O(n·k). The sliding version does k additions for the first window and two updates per slide after that: k + 2(n − k) updates, O(n). The lab prints both numbers; for the Fixed window preset that is 17 updates instead of 24 additions, and the gap grows with k.

A fixed window works with any integers, negative ones included: the size, not the sum, decides when a value leaves. Ties keep the first window (> rather than ≥), which the shared test fixture pins down.

Variable window: the longest run with sum ≤ limit

left = 0, sum = 0, best = (start -1, length 0)
for right in 0 .. n-1:
    sum += values[right]                 # expand
    while sum > limit:                   # shrink until valid again
        sum -= values[left]; left += 1
    if right - left + 1 > best.length: best = (left, right - left + 1)
return best

Invariant (checked after the shrink loop): sum equals the sum of values[left..right], that sum is ≤ limit, and left is the smallest start for which the run ending at right is valid. So right − left + 1 is the longest valid run ending at right, and the best over all right is the answer.

Why the values must be non-negative

Dropping values[left] for good is justified only if no valid run can still start there. With non-negative values that is guaranteed:

  • adding a value never decreases the sum, so if [left, right] is too big, every longer run [left, right′] with right′ ≥ right is too big as well: left can be discarded for good;
  • removing a value never increases the sum, so shrinking moves toward validity.

A single negative value breaks both. With limit 3 and values [5, −4, 1], the run [0, 2] sums to 2 and is valid, but the window drops 5 as soon as it sees sum = 5 > 3 and never reconsiders it: the algorithm answers 2 instead of 3. The lab rejects negative values in this mode for that reason; with negative values, use prefix sums (next lesson) or a monotonic deque instead.

The limit itself must be ≥ 0 for the same reason: the empty window has sum 0 and must count as valid so that the shrink loop always stops.

Why it is O(n) despite the nested loop

The while loop sits inside the for loop, but left only ever moves forward and never passes right + 1. Over the whole run, right advances n times and left advances at most n times, so the total number of sum updates is at most 2n. The lab's Sum updates metric never exceeds 2 × n; on the Value over the limit preset a single 9 forces the window to empty completely, and the count still stays within the bound.

Complexity

Version Time Extra space
Every subarray, summed directly O(n³) (O(n²) with a running sum per start) O(1)
Fixed window, recomputed O(n·k) O(1)
Fixed window, sliding O(n) O(1)
Variable window, expand/shrink O(n): ≤ 2n updates O(1)
Variable window with a frequency map (e.g. distinct letters) O(n) expected O(alphabet)

Beyond sums

The same skeleton works whenever the summary can be updated incrementally:

  • Counts or frequencies: "longest substring without a repeated letter" keeps a map from letter to count and shrinks while some count exceeds 1. See The longest stretch without a repeated letter.
  • Fixed window of totals: The busiest stretch of k hours is exactly the fixed-size algorithm above.
  • Maximum or minimum of every window: a sum can be updated by subtraction, a maximum cannot (when the maximum leaves, what is the next one?). That needs a monotonic deque, covered with queues and deques.

When the window is not monotonic (adding an element can make a bad window good again), the pattern does not apply. "Number of subarrays with sum exactly k" on arrays with negative values is the classic case; it is solved with prefix sums and a hash map in How many stretches add up to k?.

Language notes

Overflow. A window of 32-bit values can sum past 2³¹ − 1. The listings keep sums in long (C#, Java) or std::int64_t (C++). There is a second, easy-to-miss trap in the slide step: values[right] - values[right - k] is computed in int before it is added to the 64-bit sum, and the difference of two ints can overflow too. The listings widen first: (long)values[right] - values[right - k]. Python integers have arbitrary precision. If you would rather detect overflow than avoid it, C# has checked arithmetic and Java has Math.addExact.

Signed indices in C++. The variable version uses std::ptrdiff_t so that best_start can be −1 and right − left + 1 cannot wrap around when the window is empty (left = right + 1).

Library support.

Language Windows built in Notes
C# none for sliding windows (Chunk splits into non-overlapping blocks) write the loop
Python itertools docs include a sliding_window recipe built on collections.deque(maxlen=k) the recipe yields tuples; summing each is O(k)
Java none write the loop
C++23 std::views::slide(values, k) a view of overlapping subranges; summing each is still O(k)

The library views give you the windows, not the O(1) update: summing each window they produce is the O(n·k) approach. The incremental update is the point of the technique.

The teaching implementation

MaxSumOfK / max_sum_of_k and LongestWithSumAtMost / longest_with_sum_at_most are written the same way in all four languages. Each language reads one shared fixture (empty array, one value, k = n, invalid k, negatives, ties, zeros, a value above the limit, extremes) in which rows with negative values are marked "n/a" for the variable window: its precondition excludes them. Each language also compares both functions with a brute-force scan of every window on 1,000 random arrays, and the C#, Java and C++ tests include sums beyond the 32-bit range.

Common mistakes

  • Off-by-one on the leaving index. In a fixed window ending at right, the value that leaves is values[right − k], not values[right − k + 1].
  • Using the variable window with negative values. It returns a plausible but wrong answer; nothing fails loudly.
  • if instead of while when shrinking. One removal may not be enough to make the window valid again.
  • Recording the answer before shrinking. Only the window after the shrink loop is valid.
  • Forgetting invalid k (0, or larger than the array) in the fixed version.

Edge cases

  • Empty array: no fixed window exists (the listings reject it); the longest valid run has length 0.
  • Every value above the limit: each one enters and immediately leaves; the answer is length 0.
  • Limit 0: only runs of zeros qualify.
  • k = n: one window, no slides.

Worked practice

1. Largest sum of 2 consecutive values in [3, −1, 4, −1, 5]?

Answer

Windows: 2, 3, 3, 4. The largest is 4, starting at index 3 (−1 + 5).

2. Longest run with sum ≤ 6 in [2, 3, 1, 4, 1, 1]?

Answer

Length 3. [2, 3, 1] (sum 6) is found first at start 0; [4, 1, 1] also has length 3 but does not beat it, so the result is start 0, length 3.

3. Give an input with a negative value where "shrink while too big" fails.

Answer

Limit 3, values [5, −4, 1]. The correct answer is the whole array (sum 2, length 3); the window discards 5 immediately and ends with length 2.

4. Why is the shrink loop O(n) in total and not O(n) per step?

Answer

Every iteration of the inner loop moves left forward by one, and left never moves back or past right + 1. So across the whole run the inner loop executes at most n times in total.

Summary

  • A window is a contiguous range plus a summary that can be updated from the entering and leaving values.
  • Fixed windows: add one, subtract one; O(n) instead of O(n·k); any integers.
  • Variable windows: expand on the right, shrink from the left while invalid; correct when the validity is monotonic, for sums that means non-negative values.
  • Each index enters and leaves at most once, so the nested loop is O(n) overall.
  • Keep sums in 64 bits in C#, Java and C++, and widen before subtracting.

Full implementation

Both windows in four languages, each checked against one shared fixture (empty, one element, k = n, invalid k, negatives, ties, zeros, a value above the limit, extremes) and 1,000 random arrays compared with a brute-force scan of every window; C#, Java and C++ also test sums beyond the 32-bit limit.

namespace Bekadan.Dsa.Examples.ArrayPatterns;
 
/// <summary>
/// Sliding-window scans over an int array. Both run in O(n) time and O(1)
/// extra space. Window sums are kept in <see cref="long"/>: a sum of many ints
/// can exceed int.MaxValue.
/// </summary>
public static class SlidingWindow
{
    /// <summary>
    /// The largest sum of <paramref name="k"/> consecutive values and the start
    /// of the first window that has it. Any integers are allowed.
    /// </summary>
    /// <exception cref="ArgumentOutOfRangeException">k is not in 1..values.Length.</exception>
    public static (long Sum, int Start) MaxSumOfK(ReadOnlySpan<int> values, int k)
    {
        if (k < 1 || k > values.Length)
            throw new ArgumentOutOfRangeException(nameof(k), "k must be from 1 to the number of values.");
        long sum = 0;
        for (int i = 0; i < k; i++)
            sum += values[i];
        long best = sum;
        int bestStart = 0;
        for (int right = k; right < values.Length; right++)
        {
            sum += (long)values[right] - values[right - k];  // widen first: int - int can overflow
            if (sum > best)
            {
                best = sum;
                bestStart = right - k + 1;
            }
        }
        return (best, bestStart);
    }
 
    /// <summary>
    /// The first longest run of consecutive values whose sum is at most
    /// <paramref name="limit"/>: (start, length), or (-1, 0) if none.
    /// Precondition: every value is non-negative and limit &gt;= 0. With a
    /// negative value, shrinking could raise the sum and the result is wrong.
    /// </summary>
    public static (int Start, int Length) LongestWithSumAtMost(ReadOnlySpan<int> values, long limit)
    {
        int left = 0, bestStart = -1, bestLength = 0;
        long sum = 0;
        for (int right = 0; right < values.Length; right++)
        {
            sum += values[right];
            while (sum > limit)
            {
                sum -= values[left];
                left++;
            }
            if (right - left + 1 > bestLength)
            {
                bestLength = right - left + 1;
                bestStart = left;
            }
        }
        return (bestStart, bestLength);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/ArrayPatterns/SlidingWindow.cs

"""Sliding-window scans over a list of ints.
 
Both run in O(n) time and O(1) extra space. Python ints have arbitrary
precision, so window sums cannot overflow.
"""
 
from collections.abc import Sequence
 
 
def max_sum_of_k(values: Sequence[int], k: int) -> tuple[int, int]:
    """(sum, start) of the first window of k consecutive values with the largest sum.
 
    Any integers are allowed. Raises ValueError unless 1 <= k <= len(values).
    """
    if not 1 <= k <= len(values):
        raise ValueError("k must be from 1 to the number of values")
    total = 0
    for i in range(k):
        total += values[i]
    best = total
    best_start = 0
    for right in range(k, len(values)):
        total += values[right] - values[right - k]  # one value enters, one leaves
        if total > best:
            best = total
            best_start = right - k + 1
    return best, best_start
 
 
def longest_with_sum_at_most(values: Sequence[int], limit: int) -> tuple[int, int]:
    """(start, length) of the first longest run with sum <= limit, or (-1, 0).
 
    Precondition: every value is non-negative and limit >= 0. With a negative
    value, shrinking could raise the sum and the result would be wrong.
    """
    left, best_start, best_length = 0, -1, 0
    total = 0
    for right in range(len(values)):
        total += values[right]
        while total > limit:
            total -= values[left]
            left += 1
        if right - left + 1 > best_length:
            best_length = right - left + 1
            best_start = left
    return best_start, best_length

Tested on CPython 3.14.0 · examples/python/dsa_examples/sliding_window.py

package dev.bekadan.dsa.patterns;
 
/**
 * Sliding-window scans over an int array. Both run in O(n) time and O(1) extra
 * space. Window sums are kept in {@code long}: a sum of many ints can exceed
 * Integer.MAX_VALUE.
 */
public final class SlidingWindow {
    private SlidingWindow() {
    }
 
    /**
     * The largest sum of k consecutive values and the start of the first
     * window that has it: {sum, start}. Any integers are allowed.
     *
     * @throws IllegalArgumentException if k is not in 1..values.length
     */
    public static long[] maxSumOfK(int[] values, int k) {
        if (k < 1 || k > values.length) {
            throw new IllegalArgumentException("k must be from 1 to the number of values");
        }
        long sum = 0;
        for (int i = 0; i < k; i++) {
            sum += values[i];
        }
        long best = sum;
        int bestStart = 0;
        for (int right = k; right < values.length; right++) {
            sum += (long) values[right] - values[right - k]; // widen first: int - int can overflow
            if (sum > best) {
                best = sum;
                bestStart = right - k + 1;
            }
        }
        return new long[] {best, bestStart};
    }
 
    /**
     * The first longest run of consecutive values whose sum is at most limit:
     * {start, length}, or {-1, 0} if none. Precondition: every value is
     * non-negative and limit &gt;= 0. With a negative value, shrinking could
     * raise the sum and the result would be wrong.
     */
    public static int[] longestWithSumAtMost(int[] values, long limit) {
        int left = 0, bestStart = -1, bestLength = 0;
        long sum = 0;
        for (int right = 0; right < values.length; right++) {
            sum += values[right];
            while (sum > limit) {
                sum -= values[left];
                left++;
            }
            if (right - left + 1 > bestLength) {
                bestLength = right - left + 1;
                bestStart = left;
            }
        }
        return new int[] {bestStart, bestLength};
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/patterns/SlidingWindow.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <span>
#include <stdexcept>
#include <utility>
 
namespace bekadan::dsa {
 
// Sliding-window scans over a span of ints. Both run in O(n) time and O(1) extra
// space. Window sums are std::int64_t: a sum of many ints can exceed INT_MAX,
// and signed overflow is undefined behaviour.
 
// The largest sum of k consecutive values and the start of the first window
// that has it: {sum, start}. Any integers are allowed.
// Throws std::invalid_argument unless 1 <= k <= values.size().
inline std::pair<std::int64_t, std::size_t> max_sum_of_k(std::span<const int> values, std::size_t k) {
    if (k < 1 || k > values.size()) throw std::invalid_argument("k must be from 1 to the number of values");
    std::int64_t sum = 0;
    for (std::size_t i = 0; i < k; ++i) {
        sum += values[i];
    }
    std::int64_t best = sum;
    std::size_t best_start = 0;
    for (std::size_t right = k; right < values.size(); ++right) {
        sum += std::int64_t{values[right]} - values[right - k];  // widen first: int - int can overflow
        if (sum > best) {
            best = sum;
            best_start = right - k + 1;
        }
    }
    return {best, best_start};
}
 
// The first longest run of consecutive values whose sum is at most limit:
// {start, length}, or {-1, 0} if none. Precondition: every value is
// non-negative and limit >= 0. With a negative value, shrinking could raise the
// sum and the result would be wrong.
inline std::pair<std::ptrdiff_t, std::ptrdiff_t> longest_with_sum_at_most(std::span<const int> values, std::int64_t limit) {
    std::ptrdiff_t left = 0, best_start = -1, best_length = 0;
    std::int64_t sum = 0;
    for (std::ptrdiff_t right = 0; right < std::ssize(values); ++right) {
        sum += values[right];
        while (sum > limit) {
            sum -= values[left];
            ++left;
        }
        if (right - left + 1 > best_length) {
            best_length = right - left + 1;
            best_start = left;
        }
    }
    return {best_start, best_length};
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/sliding_window.hpp

References