Sliding Window — definition.
Definition
Maintain a contiguous range and slide its boundaries to avoid recomputation.
Complexity
Time O(n), space O(1) or O(k) for a frequency map.
When to use it
- Contiguous subarray or substring constraint.
- You can move one boundary based on a monotone condition.
- Brute force is O(n·k) or O(n²).
Representative scenarios
- Pharmacy Pickup — longest window with ≤ k distinct items.
- Rolling Peak Sensor — max in every window of size k.
- Unique DNA Run — longest substring with no repeated character.
Related patterns
Read the full pattern page: Sliding Window — template, code, and drills.
Run the free diagnostic.
Ten-minute patterns quiz. No card. Personalized loop starts on the other side.