Beginner Topic 17 of 51 Algorithms
Sliding Window
Maintaining a moving range to solve subarray problems in linear time.
How it works
The sliding-window technique maintains a contiguous range of a sequence and updates its summary, such as a sum, count or set of characters, incrementally as the window moves, instead of recomputing from scratch. Windows can be fixed in size or variable, expanding on the right and shrinking from the left to satisfy a condition. This turns many O(n times k) tasks into O(n).
Step-by-step walkthrough
- Find the best sum of 3 consecutive numbers.
- The first window 2 1 5 has sum 8.
- Slide right: add the new value 1 and subtract the old value 2 to get 7.
- Slide again: add 3 and drop 1 giving 9.
- The last slide gives 6, the best is 9 and the total work is O(n) instead of O(n k).
Where it is used
Maximum sum of k consecutive elements, longest substring without repeating characters, minimum window containing required characters, rate limiting over recent time, moving averages and network packet analysis use sliding windows.
Common pitfall
Incorrect window updates, such as forgetting to remove the element leaving the window, give wrong answers. It needs a monotone property: negative numbers can break shrink-on-condition logic. Use a hash map or deque to track the window contents, and test boundary windows.
Where it fits in the course
Sliding Window is topic 17 of 51 in Algorithms, rated Beginner. It follows Two Pointers. The next topic is Heap Sort.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Sliding Window?
Where do people use Sliding Window?
What is the most common mistake with Sliding Window?
What should I learn before this topic?
How can I practice it?
Is Sliding Window hard to learn?
How long does it take to learn Sliding Window?
Which topics are related to Sliding Window?
What should I study after Sliding Window?
Related topics
- Two Pointers (Algorithms)
- Heap Sort (Algorithms)
- Brute Force (Algorithms)
- Shell Sort (Algorithms)
- Sliding Window Protocol (Computer Networks)
- Window Functions (Databases)