Patterns (two pointers, windows, prefix sums) · O(n)

Sliding window

Fixed-size window sums and the longest window with sum at most a limit.

The full explanation, derivation and practice are in the lesson Sliding window: fixed and variable windows.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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