Introduction to Sliding Window

Let’s go over the Sliding Window pattern, its real-world applications, and some problems we can solve with it.

About the pattern

Imagine you have a tray of 10 cookies and want to find the most chocolate chips in any 3 cookies next to each other. You must count the chips in every possible group of 3 cookies to do this. It might seem easy with just 10 cookies, but imagine doing the same when there are thousands or more. This can become time-consuming. We can avoid this hassle by using a smarter approach. Instead of recounting the chips for each group from scratch, you start by counting the chips in the first 3 cookies. Then, as you move to the next group, you simply subtract the chips from the cookie you leave behind and add the chips from the new cookie you include. This way, you quickly check each group without starting over every time. This smart technique is called the sliding window pattern.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.