# sliding window

> a window slides along the array, adding on the right and dropping on the left.

source: https://learning.anthnydas.com/algos/sliding-window/

## tl;dr

a window is a run of the array, a[lo:hi), that only moves right. the item at hi enters, the item at lo leaves, and whatever the window keeps about its items, a sum or a count per letter, changes by those two alone.

- **one pass:** O(n) (every item enters once and leaves at most once)
- **one slide:** O(1) (add what enters, drop what leaves)
- **extra space:** O(1) (a sum, or a count per letter)
- **from scratch:** O(n·k) (every window of k, summed again)
- **one direction:** no undo (once an item leaves it can't matter again, or the window can't tell)
- **reach for it:** the biggest, smallest or average of every k items in a row, the longest run with no repeats, at most k distinct letters, or at most k zeros, the shortest run that covers something, a sum of at least s or every letter of a pattern, a pattern's anagrams in a text, as a window of letter counts, rolling statistics over the last n events

a sliding window is a run of the array, from lo up to hi, that only ever moves right. a question about every run of k items, or about the longest run with some property, sounds like it needs every run looked at in full. it doesn't. when the window moves, one item enters on the right and one leaves on the left, and whatever the window keeps about its items, a sum or a count per letter, changes by those two alone. every item enters once and leaves at most once, so the whole pass is O(n).

## the idea

> **interactive figure:** an animation in six steps over the numbers 2, 5, 1, 8, 2, 9, 1 and 3, drawn as bars with a bracket over the window and a readout of the running sum, the best so far and the steps taken. first the bracket grows over the first three bars, which turn cyan as they enter, and the sum reads 8. then it slides one step right: 8 enters in white and 2 leaves in amber before it dims, and the readout shows 8 + 8 = 16, then 16 - 2 = 14, while the 5 and the 1 in the middle stay as they are. then 2 enters and 5 leaves, 11. then 9 enters and 1 leaves, 19, and a white line under the bars marks 8 2 9 as the best so far. then two more slides, to 12 and 13, that don't move the line. last, the best stays at 19 and the readout counts 13 steps: 8 items entered and 5 left.

eight numbers and a window of 3. the first window is the first three items: 2 + 5 + 1 = 8.

slide one step right. 8 enters on the right and 2 leaves on the left: 8 + 8 - 2 = 14. the 5 and the 1 in the middle aren't touched.

again: 2 enters, 5 leaves, 14 + 2 - 5 = 11. summing the window again would be 3 steps every time. the slide is 2, however wide the window is.

9 enters, 1 leaves: 19. that's the best so far, so remember where it is.

two more slides, to 12 and 13. neither beats 19.

done: 19, the window 8 2 9. 8 items entered and 5 left, 13 steps for 6 windows. summing each window from scratch would have been 18.

## watch it run

the window above never changes size. the other kind grows and shrinks. here it hunts the longest run of letters with no letter twice: a letter enters on the right, and if it's in the window already, letters leave on the left until it isn't. the pseudocode under the figure follows along.

> **interactive figure:** an interactive stepper over a string, slidingwindow to start, with its letters in a row of numbered cells and the window as a bracket over them, lo marked under its first cell and hi under its last. the cells in the window are cyan, the letter that just entered is white, letters that have left are dim, and while the new letter is in the window twice its earlier copy is amber. each step a letter enters, or one leaves from the left, or the best is checked, and the matching pseudocode line is highlighted, with counts of the letters that have entered and left, the window's length and the best run so far. on slidingwindow the second i, at 4, makes s, l and i leave one at a time, and the longest run is gwindo, 6 letters, found after 13 enters and 8 leaves. a menu picks tomatoes, pineapples or abcabcbb instead, and a button makes 12 random letters from a to h.

## try it

a slide is one addition and one subtraction. a shrink is a jump past the earlier copy. make the calls.

> **interactive figure:** a practice exercise. some questions show a window of numbers as bars, the next one outlined white, and ask for the sum after it slides one step right, with the traps as choices: adding without dropping, dropping without adding, and dropping the wrong item. others ask you to tap the bar where the window of k with the biggest sum starts, and show that window when you have. the rest show a row of letters with the window over it and the letter about to enter in white, and ask you to tap where lo lands, or ask for the longest run with no letter twice in a short word.

## pseudocode

```text
max_sum(a, k):  # the biggest sum of k items in a row
  if not 1 <= k <= len(a): error "no window of k items"
  sum = 0
  for i in range(k):  # the first window
    sum += a[i]
  best = sum
  for i in range(k, len(a)):
    sum += a[i]  # a[i] enters on the right
    sum -= a[i - k]  # a[i - k] leaves on the left
    best = max(best, sum)
  return best

longest_unique(s):  # the longest run with no letter twice
  count = {}  # how many of each letter the window holds
  lo, best = 0, 0
  for hi in range(len(s)):
    count[s[hi]] += 1  # s[hi] enters on the right
    while count[s[hi]] > 1:  # in twice: shrink from the left
      count[s[lo]] -= 1; lo += 1  # s[lo] leaves
    best = max(best, hi - lo + 1)
  return best
```

two shapes. the first window is fixed: k items, one slide per step, and a slide is an enter and a leave. the second grows and shrinks: hi moves every step, and lo catches up only when it has to. in both, lo and hi only ever go up, and that's what the count below hangs on.

## enter once, leave once, up close

> **interactive figure:** two rows of the 13 letters of slidingwindow. the first shows the longest-run window's work: a cyan in mark under every letter, and an amber out mark under the first 8, which left. no letter has more than the two: 13 in, 8 out, 21 steps. the second row shows every start extended until a repeat: under each letter, how many times it was read, 1, 2, 3, 4, 5, 3, 4, 5, 6, 5, 5, 6 and 7, which is 56 reads in all, the last w 7 times.

- **two counters.** hi moves right once per turn of the outer loop: n enters in all. lo only moves right, and never past hi, so it moves at most n times: at most n leaves. the inner loop looks like it could run long, and on some turns it does, but over the whole pass its turns add up to at most n
- **so the pass is O(n).** at most 2n steps, however the window grew and shrank along the way. on slidingwindow it's 13 enters and 8 leaves, 21 steps. the fixed window is exact: k for the first window and 2 per slide, 2n - k
- **the cost is amortized.** one turn of the outer loop can cost up to n, when a repeat deep in the window makes everything before it leave. the enters before it paid for that, the way the pushes before a [dynamic array](/ds/dynamic-array/)'s copy pay for the copy
- **the condition that makes it work.** the window only moves right because once an item leaves it never matters again: a longer run that holds a repeat still holds it. when that isn't so, the window can't tell, and this is the wrong tool

## complexity

|                        | window | from scratch |
| ---------------------- | ------ | ------------ |
| biggest sum of k       | O(n)   | O(n·k)       |
| longest run, no repeat | O(n)   | O(n²)        |
| one slide              | O(1)   | O(k)         |
| extra space            | O(1)   | O(1)         |

from scratch means a loop over every window that sums or checks it in full. for the fixed window that's k per window and n - k + 1 windows: n·k. for the longest run it's every substring, n(n + 1) / 2 of them, each read until its first repeat. the extra space is a sum, or a count per letter: 26 of them, or a [hash table](/ds/hash-table/) for a bigger alphabet.

> **interactive figure:** a line chart of steps per item against how many items there are, from 16 to 4,096 on a doubling scale, with a slider that picks a size and reads off every line. per item, a line that stays flat is linear time. the window, solid cyan, stays at about 2 steps per item: 1.5 at 16 and 2 at 4,096. recomputing every window of 8, dashed amber, settles at 8: 4.5 at 16 and 7.99 at 4,096. every start extended until a repeat, dotted, climbs slowly toward 7: 3.56 at 16 and 6.95 at 4,096, since no run of letters passes 26. checking every substring, amber, is off the top of the chart from the first point: 27 steps per item at 16 and 14,174 at 4,096.

on 4,096 numbers the window took 8,184 steps, and summing every window of 8 from scratch 32,712: 4 times as many, and k / 2 times in general. on 4,096 random letters the longest-run window took 8,191 steps, and checking every substring 58,056,286: there are 8,390,656 substrings before a single letter is read. trying every start and stopping at the first repeat does better than it sounds: with 26 letters no run passes 26, so it read about 7 letters per start, 28,468 in all. that's still 3 and a half times the window, and over items with no such cap, numbers say, it's n² again.

## implementations

each tab is the real file from the repo, checked by its tests (`go test`, `cargo test`, `vitest`, `make test`, `swift test`, `python -m unittest`), including 2000 seeded arrays against every window summed from scratch, 2000 seeded strings against every start extended until a repeat, and a million items in one pass, 100,000 in python. the longest run counts the string's utf-8 bytes, so every tab agrees on any string: a letter outside ascii counts as the 2 to 4 bytes it takes. k outside 1 to n has no window: typescript and python say so with an error, go answers `false`, rust `None`, swift `nil`, and c `false`.

`go/algos/slidingwindow/slidingwindow.go`

```go
// Package slidingwindow is a reference for two sliding windows. a window is a run of items, a[lo:hi), that
// only ever moves right: the item at hi enters, the item at lo leaves, and whatever the window keeps (a
// sum, a count per letter) is updated by those two items alone instead of being worked out again from
// scratch. every item enters once and leaves at most once, so a whole pass is O(n), however wide the
// window gets.
package slidingwindow

// MaxSum returns the biggest sum of k items in a row, and true. The first k items make the first window;
// then each step adds the item entering on the right and takes away the one leaving on the left. k has to
// be 1 to len(a): there's no run of 0 items, and none longer than the slice. Any other k gets 0 and false.
func MaxSum(a []int, k int) (int, bool) {
	if k < 1 || k > len(a) {
		return 0, false
	}
	sum := 0
	for _, x := range a[:k] {
		sum += x
	}
	best := sum
	for i := k; i < len(a); i++ {
		sum += a[i]   // a[i] enters on the right
		sum -= a[i-k] // a[i - k] leaves on the left
		best = max(best, sum)
	}
	return best, true
}

// LongestUnique returns the length of the longest run with no letter twice. The window grows by one on the
// right each step, and when the new letter is in it already, shrinks from the left until it isn't. Counted
// over the string's utf-8 bytes, so every tab agrees: a letter outside ascii counts as the 2 to 4 bytes it
// takes. s[i] is a byte, where range s would step a whole rune at a time.
func LongestUnique(s string) int {
	var count [256]int // how many of each byte the window holds
	lo, best := 0, 0
	for hi := 0; hi < len(s); hi++ {
		count[s[hi]]++ // s[hi] enters on the right
		for count[s[hi]] > 1 {
			count[s[lo]]-- // s[lo] leaves on the left
			lo++
		}
		best = max(best, hi-lo+1)
	}
	return best
}
```

`rust/algos/src/sliding_window.rs`

```rust
//! two sliding windows. a window is a run of items, a[lo:hi), that only ever moves right: the item at hi enters, the item at lo leaves, and whatever the window keeps (a sum, a count per letter) is updated by those two items alone instead of being worked out again from scratch. every item enters once and leaves at most once, so a whole pass is O(n), however wide the window gets.

/// The biggest sum of `k` items in a row, or `None` when there's no window of `k`. The first `k`
/// items make the first window; then each step adds the item entering on the right and takes away
/// the one leaving on the left. `k` has to be 1 to n: there's no run of 0 items, and none longer
/// than the slice. The sum is an `i64`: a window of big `i32`s can add up past `i32::MAX`.
pub fn max_sum(a: &[i32], k: usize) -> Option<i64> {
    if k == 0 || k > a.len() {
        return None;
    }
    let mut sum: i64 = a[..k].iter().map(|&x| i64::from(x)).sum();
    let mut best = sum;
    for i in k..a.len() {
        sum += i64::from(a[i]); // a[i] enters on the right
        sum -= i64::from(a[i - k]); // a[i - k] leaves on the left
        best = best.max(sum);
    }
    Some(best)
}

/// The length of the longest run with no letter twice. The window grows by one on the right each
/// step, and when the new letter is in it already, shrinks from the left until it isn't. Counted
/// over the string's utf-8 bytes, so every tab agrees: a letter outside ascii counts as the 2 to 4
/// bytes it takes.
pub fn longest_unique(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut count = [0u32; 256]; // how many of each byte the window holds
    let mut lo = 0;
    let mut best = 0;
    for hi in 0..bytes.len() {
        count[bytes[hi] as usize] += 1; // bytes[hi] enters on the right
        while count[bytes[hi] as usize] > 1 {
            count[bytes[lo] as usize] -= 1; // bytes[lo] leaves on the left
            lo += 1;
        }
        best = best.max(hi - lo + 1);
    }
    best
}

#[cfg(test)]
mod tests {
    use super::*;

    /// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
    fn xorshift32(seed: u32) -> impl FnMut() -> usize {
        let mut state = seed;
        move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        }
    }

    /// Every window of k summed from scratch, and the biggest sum: the brute force.
    fn sum_from_scratch(a: &[i32], k: usize) -> Option<i64> {
        a.windows(k)
            .map(|w| w.iter().map(|&x| i64::from(x)).sum())
            .max()
    }

    /// Every start, extended until a repeat: the brute force.
    fn longest_from_scratch(s: &str) -> usize {
        let b = s.as_bytes();
        let mut best = 0;
        for lo in 0..b.len() {
            let mut seen = [false; 256];
            let mut hi = lo;
            while hi < b.len() && !seen[b[hi] as usize] {
                seen[b[hi] as usize] = true;
                hi += 1;
            }
            best = best.max(hi - lo);
        }
        best
    }

    const LOWERCASE: &[u8] = b"abcdefghijklmnopqrstuvwxyz";

    /// `n` letters, each drawn from `alphabet`.
    fn letters(n: usize, next: &mut impl FnMut() -> usize, alphabet: &[u8]) -> String {
        (0..n)
            .map(|_| alphabet[next() % alphabet.len()] as char)
            .collect()
    }

    // max sum

    #[test]
    fn the_page_example_2_5_1_8_2_9_1_3_with_k_equals_3_is_19_the_window_8_2_9() {
        assert_eq!(max_sum(&[2, 5, 1, 8, 2, 9, 1, 3], 3), Some(19));
    }

    #[test]
    fn k_equals_1_is_the_biggest_item_and_k_equals_n_is_the_whole_sum() {
        assert_eq!(
            (
                max_sum(&[3, 9, 4], 1),
                max_sum(&[3, 9, 4], 3),
                max_sum(&[7], 1)
            ),
            (Some(9), Some(16), Some(7))
        );
    }

    #[test]
    fn negative_numbers_the_best_window_can_sum_to_less_than_0() {
        assert_eq!(max_sum(&[-5, -2, -9, -1], 2), Some(-7));
    }

    #[test]
    fn k_outside_1_to_n_has_no_window_and_neither_has_an_empty_array() {
        for k in [0, 9] {
            assert_eq!(max_sum(&[2, 5, 1, 8, 2, 9, 1, 3], k), None, "k = {k}");
        }
        assert_eq!(max_sum(&[], 1), None);
    }

    #[test]
    fn agrees_with_every_window_summed_from_scratch_over_2000_seeded_arrays() {
        let mut next = xorshift32(42);
        for _ in 0..2000 {
            let n = 1 + next() % 40;
            let a: Vec<i32> = (0..n).map(|_| (next() % 21) as i32 - 10).collect();
            let k = 1 + next() % n;
            assert_eq!(max_sum(&a, k), sum_from_scratch(&a, k));
        }
    }

    #[test]
    fn a_million_items_in_one_pass_checked_with_prefix_sums() {
        let mut next = xorshift32(7);
        let (n, k) = (1_000_000, 1000);
        let a: Vec<i32> = (0..n).map(|_| (next() % 100) as i32).collect();
        // prefix[i] is the sum of the first i items, so a window's sum is one subtraction
        let mut prefix = vec![0i64; n + 1];
        for (i, &x) in a.iter().enumerate() {
            prefix[i + 1] = prefix[i] + i64::from(x);
        }
        let want = (k..=n).map(|hi| prefix[hi] - prefix[hi - k]).max();
        assert_eq!(max_sum(&a, k), want);
    }

    // longest unique

    #[test]
    fn the_page_example_slidingwindow_is_6_the_run_gwindo() {
        assert_eq!(longest_unique("slidingwindow"), 6);
    }

    #[test]
    fn empty_is_0_one_letter_is_1_one_letter_over_and_over_is_1_all_different_is_the_whole_string()
    {
        assert_eq!(
            ["", "a", "aaaaa", "abcdefg"].map(longest_unique),
            [0, 1, 1, 7]
        );
    }

    #[test]
    fn abba_is_2_after_the_second_b_the_window_is_just_b_then_ba() {
        assert_eq!(longest_unique("abba"), 2);
    }

    #[test]
    fn counts_utf_8_bytes_é_is_2_of_them_and_so_is_éé() {
        assert_eq!(["é", "éé", "aéb"].map(longest_unique), [2, 2, 4]);
    }

    #[test]
    fn agrees_with_every_start_extended_until_a_repeat_over_2000_seeded_strings() {
        let mut next = xorshift32(42);
        for round in 0..2000 {
            let n = next() % 30;
            // a small alphabet makes repeats common; the full one makes long runs
            let alphabet: &[u8] = if round % 2 == 1 { b"abcd" } else { LOWERCASE };
            let s = letters(n, &mut next, alphabet);
            assert_eq!(longest_unique(&s), longest_from_scratch(&s));
        }
    }

    #[test]
    fn a_million_letters_in_one_pass_agrees_with_every_start() {
        let s = letters(1_000_000, &mut xorshift32(7), LOWERCASE);
        assert_eq!(longest_unique(&s), longest_from_scratch(&s));
    }
}
```

`site/src/visuals/sliding-window/sliding-window.ts`

```ts
/**
 * Two sliding windows. A window is a run of items, a[lo:hi), that only ever moves right: the item at hi enters, the
 * item at lo leaves, and whatever the window keeps (a sum, a count per letter) is updated by those two items alone
 * instead of being worked out again from scratch. Every item enters once and leaves at most once, so a whole pass
 * is O(n), however wide the window gets.
 */

/**
 * The biggest sum of k items in a row. The first k items make the first window; then each step adds the item
 * entering on the right and takes away the one leaving on the left. k has to be 1 to n: there's no run of 0 items,
 * and none longer than the array.
 */
export function maxSum(a: readonly number[], k: number): number {
  if (!Number.isInteger(k) || k < 1 || k > a.length)
    throw new RangeError(`no window of ${k} items in ${a.length}`);
  let sum = 0;
  for (let i = 0; i < k; i++) sum += a[i];
  let best = sum;
  for (let i = k; i < a.length; i++) {
    sum += a[i]; // a[i] enters on the right
    sum -= a[i - k]; // a[i - k] leaves on the left
    if (sum > best) best = sum;
  }
  return best;
}

/**
 * The length of the longest run with no letter twice. The window grows by one on the right each step, and when the
 * new letter is in it already, shrinks from the left until it isn't. Counted over the string's utf-8 bytes, so every
 * tab agrees: a letter outside ascii counts as the 2 to 4 bytes it takes.
 */
export function longestUnique(s: string): number {
  const bytes = new TextEncoder().encode(s);
  const count = new Uint32Array(256); // how many of each byte the window holds
  let lo = 0;
  let best = 0;
  for (let hi = 0; hi < bytes.length; hi++) {
    count[bytes[hi]] += 1; // bytes[hi] enters on the right
    while (count[bytes[hi]] > 1) {
      count[bytes[lo]] -= 1; // bytes[lo] leaves on the left
      lo += 1;
    }
    if (hi - lo + 1 > best) best = hi - lo + 1;
  }
  return best;
}
```

`c/algos/sliding_window.c`

```c
/* two sliding windows. a window is a run of items, a[lo..hi), that only ever moves right: the item at hi enters, the item at lo leaves, and whatever the window keeps (a sum, a count per letter) is updated by those two items alone instead of being worked out again from scratch. every item enters once and leaves at most once, so a whole pass is O(n), however wide the window gets. */
#include "sliding_window.h"

/* the first k items make the first window; then each step adds the item entering on the right and
   takes away the one leaving on the left. the sum is a long long, since k ints can add up to more
   than an int holds */
bool max_sum(const int *a, size_t n, size_t k, long long *best_out) {
    if (k == 0 || k > n) return false; /* no run of 0 items, and none longer than the array */
    long long sum = 0;
    for (size_t i = 0; i < k; i++) sum += a[i];
    long long best = sum;
    for (size_t i = k; i < n; i++) {
        sum += a[i]; /* a[i] enters on the right */
        sum -= a[i - k]; /* a[i - k] leaves on the left */
        if (sum > best) best = sum;
    }
    *best_out = best;
    return true;
}

/* the window grows by one on the right each step, and when the new byte is in it already, shrinks
   from the left until it isn't. bytes are read as unsigned char: a plain char can be signed, and
   then 0xc3 would index count[-61] */
size_t longest_unique(const char *s) {
    const unsigned char *bytes = (const unsigned char *)s;
    size_t count[256] = {0}; /* how many of each byte the window holds */
    size_t lo = 0, best = 0;
    for (size_t hi = 0; bytes[hi] != '\0'; hi++) {
        count[bytes[hi]]++; /* bytes[hi] enters on the right */
        while (count[bytes[hi]] > 1) {
            count[bytes[lo]]--; /* bytes[lo] leaves on the left */
            lo++;
        }
        if (hi - lo + 1 > best) best = hi - lo + 1;
    }
    return best;
}
```

`swift/algos/SlidingWindow.swift`

```swift
/// two sliding windows. a window is a run of items, a[lo..<hi], that only ever moves right: the item at hi enters, the item at lo leaves, and whatever the window keeps (a sum, a count per letter) is updated by those two items alone instead of being worked out again from scratch. every item enters once and leaves at most once, so a whole pass is O(n), however wide the window gets.

/// the biggest sum of k items in a row. the first k items make the first window; then each step adds the item
/// entering on the right and takes away the one leaving on the left. k has to be 1 to n: there's no run of 0 items,
/// and none longer than the array, so any other k gets nil. each sum has to fit in an Int, or swift traps
public func maxSum(_ a: [Int], _ k: Int) -> Int? {
    if k < 1 || k > a.count { return nil }
    var sum = 0
    for i in 0..<k { sum += a[i] }
    var best = sum
    for i in k..<a.count {
        sum += a[i] // a[i] enters on the right
        sum -= a[i - k] // a[i - k] leaves on the left
        if sum > best { best = sum }
    }
    return best
}

/// the length of the longest run with no letter twice. the window grows by one on the right each step, and when
/// the new letter is in it already, shrinks from the left until it isn't. counted over the string's utf-8 bytes, so
/// every tab agrees: a letter outside ascii counts as the 2 to 4 bytes it takes
public func longestUnique(_ s: String) -> Int {
    let bytes = Array(s.utf8)
    var count = [Int](repeating: 0, count: 256) // how many of each byte the window holds
    var lo = 0
    var best = 0
    for hi in bytes.indices {
        count[Int(bytes[hi])] += 1 // bytes[hi] enters on the right
        while count[Int(bytes[hi])] > 1 {
            count[Int(bytes[lo])] -= 1 // bytes[lo] leaves on the left
            lo += 1
        }
        if hi - lo + 1 > best { best = hi - lo + 1 }
    }
    return best
}
```

`python/algos/sliding_window.py`

```python
"""two sliding windows. a window is a run of items, a[lo:hi), that only ever moves right: the item at hi enters, the item at lo leaves, and whatever the window keeps (a sum, a count per letter) is updated by those two items alone instead of being worked out again from scratch. every item enters once and leaves at most once, so a whole pass is O(n), however wide the window gets."""

from __future__ import annotations


def max_sum(a: list[int], k: int) -> int:
    """Return the biggest sum of k items in a row.

    The first k items make the first window; then each step adds the item entering on the right and takes
    away the one leaving on the left. k has to be 1 to len(a): there's no run of 0 items, and none longer
    than the list, so any other k raises ValueError.
    """
    if k < 1 or k > len(a):
        raise ValueError(f"no window of {k} items in {len(a)}")
    total = sum(a[:k])
    best = total
    for i in range(k, len(a)):
        total += a[i]  # a[i] enters on the right
        total -= a[i - k]  # a[i - k] leaves on the left
        best = max(best, total)
    return best


def longest_unique(s: str) -> int:
    """Return the length of the longest run with no letter twice.

    The window grows by one on the right each step, and when the new letter is in it already, shrinks from
    the left until it isn't. Counted over the string's utf-8 bytes, so every tab agrees: a letter outside
    ascii counts as the 2 to 4 bytes it takes.
    """
    b = s.encode()  # the utf-8 bytes
    count = [0] * 256  # how many of each byte the window holds
    lo = 0
    best = 0
    for hi in range(len(b)):
        count[b[hi]] += 1  # b[hi] enters on the right
        while count[b[hi]] > 1:
            count[b[lo]] -= 1  # b[lo] leaves on the left
            lo += 1
        best = max(best, hi - lo + 1)
    return best
```

## pitfalls

- **summing the window again.** adding up the window after every slide is k steps a slide. the whole point is the running total: one add and one drop
- **adding without dropping.** take in what enters and forget what leaves, and the window grows instead of sliding: the sum climbs and never comes down. it's the first trap in try it
- **k outside 1 to n.** with k = 0 the first window is empty and every slide adds and drops the same item. with k bigger than n there is no first window, and an unchecked loop reads past the end. every tab turns both away
- **shrinking by one.** when the letter entering is already in the window, lo has to move past the earlier copy, however deep it is. the counts and the while loop do that on their own. with a last-seen index instead, lo = max(lo, last + 1): abba is the string that breaks the version without the max
- **a window that can't tell.** the trick needs that an item which left never matters again. the longest run with a sum of at most s works on positive numbers, where a longer window always sums to more, and breaks once numbers can be negative
- **floating point.** a running sum of floats drifts: every add and drop leaves a little rounding behind, and it piles up. pandas compensates with kahan summation. for exact answers use integers, or sum from scratch now and then

## variants

- **a window of counts.** 26 counts, or a [hash table](/ds/hash-table/), hold what the window has. a pattern's anagrams in a text are the windows whose counts match the pattern's
- **at most k distinct.** grow on the right, and when the window holds more than k different letters, shrink from the left until it doesn't. windows with exactly k distinct are the ones with at most k minus the ones with at most k - 1
- **the shortest window that covers.** flip the loops: grow until the window has what's needed, a sum of at least s or every letter of a pattern, then shrink from the left while it still does, and keep the shortest. minimum window substring is this
- **sliding window maximum.** the biggest item in every window of k, with a [deque](/ds/stack-queue/) of indexes whose values go down from front to back. the front is the window's maximum; an index that leaves the window is dropped from the front, and a new item pops everything smaller off the back. each index is pushed and popped at most once, so still O(n)
- **prefix sums.** for sums alone, an array of running totals answers any range in O(1) after O(n) once. the window's running sum is the same idea, kept one window at a time
- **two pointers.** the window is the two-pointers pattern with both indexes walking the same way. the other kind starts them at the two ends

## practice

- [maximum average subarray i](https://leetcode.com/problems/maximum-average-subarray-i/): the fixed window, divided by k
- [longest substring without repeating characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/): the stepper's problem
- [minimum size subarray sum](https://leetcode.com/problems/minimum-size-subarray-sum/): the shortest window with a sum of at least s
- [max consecutive ones iii](https://leetcode.com/problems/max-consecutive-ones-iii/): at most k zeros in the window
- [permutation in string](https://leetcode.com/problems/permutation-in-string/): a fixed window of letter counts
- [sliding window maximum](https://leetcode.com/problems/sliding-window-maximum/): the deque

## how real libraries do it

- **python.** the itertools recipes have a `sliding_window`: a deque with maxlen n, so appending the next item drops the oldest by itself, and each window comes out as a tuple. the recipes double as an incubator, and this one is being tested to see whether it earns a place in itertools[^itertools]. pandas' rolling sum keeps a running total: as the window moves it removes the values that left and adds the ones that entered, with kahan summation on both so rounding doesn't pile up[^pandas]
- **numpy.** `sliding_window_view` hands back every window as one view into the same memory, so nothing is copied. its own docs put the approach at about O(n·w), where a special algorithm often manages O(n), and call a window of 100 up to 100 times slower[^numpy]
- **rust.** `slice::windows(k)` iterates every window of k as a slice. the windows overlap, and a slice shorter than k gives none. what the window keeps is up to you, so summing each one is n·k[^rust]
- **everywhere else.** it's a loop of a few lines, written where it's needed

[^itertools]: [itertools recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes) in the python docs, from [itertools.rst](https://github.com/python/cpython/blob/v3.15.0/Doc/library/itertools.rst#L944-L951) in cpython 3.15.0: `sliding_window` fills a deque with maxlen n from the first n - 1 items, then appends each next item and yields the deque as a tuple. [the recipes](https://github.com/python/cpython/blob/v3.15.0/Doc/library/itertools.rst#L817-L820) also serve as an incubator: accumulate, compress and pairwise started out as recipes, and sliding_window is being tested to see whether it proves its worth.

[^pandas]: [aggregations.pyx](https://github.com/pandas-dev/pandas/blob/v3.0.6/pandas/_libs/window/aggregations.pyx#L91-L129) in pandas 3.0.6: `add_sum` and `remove_sum` add a value to the rolling sum, and remove one from it, using kahan summation, each with its own compensation term. [`roll_sum`](https://github.com/pandas-dev/pandas/blob/v3.0.6/pandas/_libs/window/aggregations.pyx#L132-L184) sums the first window from scratch, and when the window's bounds only move forward, removes the values that left since the last window and adds the ones that entered.

[^numpy]: [\_stride_tricks_impl.py](https://github.com/numpy/numpy/blob/v2.5.4/numpy/lib/_stride_tricks_impl.py#L180-L187) in numpy 2.5.4: `sliding_window_view` creates a view of the array at every window position, also known as a rolling or moving window, and [a warning](https://github.com/numpy/numpy/blob/v2.5.4/numpy/lib/_stride_tricks_impl.py#L235-L241) says the views share overlapping memory. [its notes](https://github.com/numpy/numpy/blob/v2.5.4/numpy/lib/_stride_tricks_impl.py#L243-L260) say the approach can be very slow: as a rough estimate it scales as O(N·W) for an input of N and a window of W, where a special algorithm can often reach O(N), so a window of 100 can be 100 times slower than a specialized version.

[^rust]: [slice::windows](https://doc.rust-lang.org/std/primitive.slice.html#method.windows) in the rust docs, from [slice/mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/mod.rs#L1063-L1069) at rust 1.99.1: an iterator over all contiguous windows of length size, which overlap. a slice shorter than size gives no windows, and a size of zero panics.

## related

- https://learning.anthnydas.com/algos/two-pointers.md
- https://learning.anthnydas.com/ds/stack-queue.md
- https://learning.anthnydas.com/ds/hash-table.md
- https://learning.anthnydas.com/algos/big-o.md
