Chapter 05 - Sliding Windows

A window that slides over the array, growing on the right and shrinking on the left, instead of recomputing every subarray from scratch.

Coding Interview Patterns book cover with the Rust logo and a CHAP 05 label, the chapter on sliding windows

This page is the entry point of chapter 5 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

We keep a window [left, right] over contiguous elements, plus some state about its content (a sum, counts of characters). The right edge moves forward at every step. When the window breaks the constraint, the left edge moves forward until it is valid again. Each element enters and leaves the window once, so \(O(n)\) instead of the \(O(n^2)\) of every substring.

When to reach for it

  • The question is about a contiguous substring or subarray.
  • We want the longest, the shortest, or the number of windows that respect a constraint.
  • The window has a fixed size (anagrams of a given word) or a dynamic one (longest substring without repeated characters).

In Rust

  • For lowercase English letters, a [usize; 26] indexed by (b - b'a') as usize beats a HashMap, and two such arrays compare with ==.
  • Work on bytes (s.as_bytes()), not on chars(), when the alphabet is ASCII.
  • For a general alphabet, HashMap<char, usize> or HashSet<char> hold the window state.

Problems in this chapter

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude