Intro
The sliding window algorithm is very appropriately named.
The benefit of a sliding window is that you can let in as much sun/air as you want, by opening up the window as wide or narrow as you want.
Suppose you have a linear data structure, such as an array or a list, but are only interested in a subsection of it. For example, given an array [1, 2, 3], one subarray would be [2, 3].
There are many interview questions that are asked, which involve subsections of an array. Luckily, many of these questions can be solved by using the sliding window algorithm.
Here is the sliding window algorithm:
- Take an arbitrary subarray of the input array
- Check if the subarray satisfies the question requirement
- Expand or decrease the size or location of the subarray until the requirement is satisfied
We call it a sliding window since our subarray is essentially sliding along the input array, revealing only a subsection of the input array at any given time.
Let’s see a few examples.