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.
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 usizebeats aHashMap, and two such arrays compare with==. - Work on bytes (
s.as_bytes()), not onchars(), when the alphabet is ASCII. - For a general alphabet,
HashMap<char, usize>orHashSet<char>hold the window state.
Problems in this chapter
- p086 - Substring Anagrams: Substring Anagrams (Sliding Windows) solved in Rust: count the substrings of s that are anagrams of t, both made of lowercase English letters.
- p090 - Longest Substring With Unique Characters: Longest Substring With Unique Characters (Sliding Windows), solved in Rust. Given a string determine the lenght of its longest substring of unique char.
- p095 - Longest Uniform Substring After Replacements: Longest Uniform Substring After Replacements (Sliding Windows) solved in Rust: longest run of one character after replacing up to k characters.
Other chapters
All the chapters, with every problem, are listed on the series page.