Member-only story
Sliding Window Algorithm Explained with 38 Coding Questions and Solutions
21 min readOct 23, 2024
What is Sliding Window Algorithm
The sliding window is a data structure technique that transforms two nested loops into a single loop within an array or list.
Usually it’s for problems that have a brute force method approach that has a time complexity of O(n²) or O(n³). With the sliding window technique, it can reduce the time complexity to O(n).
Types of Questions the Algorithm will be used
When you get an interview question that involves the following points below, the problem can most likely be solved with this algorithm.
- The problem will be based on an array, list or single type of data structure
- It will ask to find subranges in that array to give the longest, shortest or target values of a string.
- Its concept is mainly based on ideas like the longest sequence or shortest sequence of something that satisfies a given condition perfectly.
How to Solve With the Algorithm
- Use a HashMap or dictionary to count a specific array input and increase the window toward the right using an outer loop.
- Take one inside a loop to reduce the window side by sliding towards the right. This loop will be very short.
- Store the current max or min window size or count based on the…