Algorithm · Array techniques · O(n)
Sliding window
Maintain a contiguous window and update its summary as it slides: fixed-size window sums, or the longest window under a limit, in O(n).
The full derivation, edge cases and exercises are in the lesson Sliding window: fixed and variable windows. Open it full width in the playground.
On this page
The idea
Recomputing every window from scratch costs O(n · k). Sliding instead adds the element entering on the right and removes the one leaving on the left. For a variable window, expand on the right and shrink from the left while the window breaks the rule.
The variable form relies on monotonicity: with non-negative values, shrinking never increases the sum. With negative values the technique is not correct and prefix sums are needed instead.
Steps
- Fixed: sum the first k values, then for each step add a[i] and subtract a[i − k].
- Variable: add a[right]; while the sum exceeds the limit, subtract a[left] and advance left; record the length.
Invariants
What holds at every step; the correctness argument rests on these.
- The running sum equals the sum of a[left … right].
- Each index enters and leaves the window at most once.
Complexity
| Case | Time | Extra space | Notes |
|---|---|---|---|
| Either form | O(n) | O(1) | Amortized: left and right each move at most n times. |
When to use it
Use it when
- Contiguous subarrays or substrings with a size or a monotonic constraint.
Avoid it when
- The elements need not be contiguous, or the constraint is not monotonic (negative values with a sum limit).
Step through it
The interactive lab for sliding window: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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 >= 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 >= 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
Learn more
Lessons
- Sliding window: fixed and variable windows· M15 Sliding Window
Data structures it uses
Problems, patterns and exercises
- PatternSliding window· O(n)
- ProblemThe busiest stretch of k hours· beginner · O(n)
- ProblemThe longest stretch without a repeated letter· intermediate · O(n) expected
- Complexity exerciseA while loop inside a for loop (sliding window)· Θ(n) (amortized O(1) per step)