Sliding Window Technique
JB
Posted on April 20, 2020
Resources:
Takeaways:
- The sliding window technique is where we use two pointers on a collection. We say that one pointer represents the start of the window and the other the end of the window. The space/elements between the two pointers is the window size.
- A sliding window can be of fixed length or it can be variable length (meaning the window expands/contracts dynamically).
- Fixed length is often easier to grasp/think about. Both pointers, say
i
andj
, in a loop are incremented by the same number each time our max window size is reached. - Variable length is where
i
orj
change at a different pace to each other. Often questions requiring this technique don't provide a window size, but ask for the largest/smallest possible window given some constraints.
- Fixed length is often easier to grasp/think about. Both pointers, say
- Here are some questions we can use the sliding window technique on:
- In an array of
n
integers, find a contiguousk
length subarray that has the largest value when it's elements are summed.- We can use two pointers here and our window would be of size
k
.
- We can use two pointers here and our window would be of size
- What is the size of the minimum subarray that when summed will equal a target sum?
- We can use two pointers here, but because we want the minimum length subarray (i.e the question is asking how big/small the window is) the window can't be of fixed length.
- What is the largest subarray of
k
distinct characters?- We can use two pointers here. This will again be a variable length window, as we are being asked what the size of the window is (largest subarray). We will also need to use an auxiliary data structure to keep track of how many distinct characters are in a given subarray.
- In an array of
- A less obvious question where sliding window would come in handy:
- Given two strings
inputA
&inputB
, determine if any permutation ofinputA
is a substring ofinputB
.- Here we can use two pointers and the window will be of fixed size/won't ever grow larger than the length of
inputA
.
- Here we can use two pointers and the window will be of fixed size/won't ever grow larger than the length of
- Given two strings
Below are solutions to all the problems mentioned. I have annotated the source code with time & space complexities for each solution:
As always, if you found any errors in this post please let me know!
💖 💪 🙅 🚩
JB
Posted on April 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.