algospatterns

sliding window

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

report a mistake
.md

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
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. enter once, leave once, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

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

sum 0best -steps 0sum 2best -steps 12 + 5 = 7best -steps 27 + 1 = 8best -steps 3sum 8best 8steps 38 + 8 = 16best 8steps 416 - 2 = 14best 8steps 5sum 14best 14steps 514 + 2 = 16best 14steps 616 - 5 = 11best 14steps 7sum 11best 14steps 711 + 9 = 20best 14steps 820 - 1 = 19best 14steps 9sum 19best 19steps 919 + 1 = 20best 19steps 1020 - 8 = 12best 19steps 11sum 12best 19steps 1112 + 3 = 15best 19steps 1215 - 2 = 13best 19steps 13sum 13best 19steps 13sum 13best 19steps 13
eight numbers and a window of 3. the first window is the first three items: 2 + 5 + 1 = 8.

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.

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.

letters

nothing in the window yet: lo is 0, and the best is 0

entered
0
left
0
window
0
best
0
step
1 of 36
pseudocode
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

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.

the window 1 8 2 sums to 11. it slides one step right. what's the sum then?

pick one.

0 / 0 right

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

pseudocode
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

the window. a mark under each letter as it enters, and another as it leaves: 13 in, 8 out, 21 steps. no letter gets a third mark

every start, until a repeat. how many times each letter is read: 56 reads in all, and one letter 7 times

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.

complexity

windowfrom scratch
biggest sum of kO(n)O(n·k)
longest run, no repeatO(n)O(n²)
one slideO(1)O(k)
extra spaceO(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 for a bigger alphabet.

0246810162564096every substring
the window
2.00 steps per item
every window of 8
7.99 steps per item
every start
6.95 steps per item
every substring
14,174 steps per item

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
// 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
//! 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
/**
 * 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
/* 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
/// 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
"""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

variants

practice

how real libraries do it

sources

  1. itertools recipes (opens in a new tab) in the python docs, from itertools.rst (opens in a new tab) 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 (opens in a new tab) 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. ↩

  2. aggregations.pyx (opens in a new tab) 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 (opens in a new tab) 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. ↩

  3. _stride_tricks_impl.py (opens in a new tab) 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 (opens in a new tab) says the views share overlapping memory. its notes (opens in a new tab) 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. ↩

  4. slice::windows (opens in a new tab) in the rust docs, from slice/mod.rs (opens in a new tab) 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. ↩