Sliding Window for Noobs like me!

Chandradhar Rao
2 min readSep 7, 2021

--

Hope someone finds this helpful.Here we go…

A window,visually can be thought of as something like a scanner that scans through items (in our case an array) sequentially.

scanner used to scan through items iteratively

It is logically defined by a start index and end index.This logically defines the window.

For example consider this question from Leetcode:

Substrings of Size Three with Distinct Characters

In this in order to find the sub-string with distinct characters with length 3,we could spin up a double for loop,but an optimised solution would be the sliding window.

Here we use the previously described logical window that starts at index i=0 and spans upto index j=i+2 (remember arrays are 0 indexed).

We know that a scanner can scan only upto a certain radius at a time.Similarly out window too can check for elements only spanned by it.

Hence iteratively we check if the elements are unique within this window (as this problem demands uniqueness)

For uniqueness s[i] != s[i+1] && s[i] != s[i+2] && s[i+1] != s[i+2] because the window size is only three.

Since this is a repetitive task,we could load it into a for loop,but i prefer a do while loop and it would look something like this:

Sliding window code

A scanner would move linearly when scanning through items placed on table.

Similarly,the window too moves one step at a time like a moving queue,where the next unseen element of the array is pushed into the queue and the top most element of the queue is popped.

In this way,we scan through the entire array.

This was it about the sliding window.Hope you took something away from this!.

--

--

Chandradhar Rao

Computer Science Undergrad by the day and Hobbyist Indie Game Developer by the Night.