The Sliding Window Technique

Sohom RoySohom Roy
5 min read

What is a Sliding Window? What does it have to do with programming? Why was it even named “Sliding Window” in the first place? All you have to do is just read.

You might’ve come across LeetCode problems like Maximum Average Subarray, Max Consecutive Ones, etc and everybody in the solutions keep talking about this Sliding Window Technique and what not! So let’s take a look and see what it actually is.

As a great man once said:

If you see the word consecutive or longest, try the the Sliding Window Technique!

Now this probably is kinda stupid and that great man is stupid and I’m stupid so you’re advised to ignore it.

Enough yapping, let’s get to the point.

Training Wheels (The Basics)

In simple words, it is used to solve problems related to arays, lists or strings when you need to work with contiguous subsets or what we call windows!

Take a look at this question.

Now as you can guess from the given example, we need to work with contiguous pieces of the data. Still didn’t get that? Alright, if you look in the question, it says you need to take subsets of the list/array of length ‘k’. Now this ‘k’ is nothing but the window size. In simple words you need to get the maximum average subarray from the given array which has length 4.

Now, you might’ve tried getting this done with regular programming logic but you ended up scratching you head for quite some time right? That’s how it is, that’s how programming is. It’s just like maths, like how we had specific ways or methods of solving different types of problems.

Now let’s look at the solution shall we?

We’ll be looking at some core points that I’m gonna mention below.

  • We’ll take an imaginary subarray that will keep sliding one by one through the elements till it reaches the end of the list/array.

  • The length of the subarray will be ‘k’ here.

  • At each step we’ll calculate the average of the subarray and if the recently calculated subarray is greater than say an already existing one then we’ll replace it. For that we’ll define a variable say max_avg.

The Code. Yes Finally after so much yapping.

Now for the code, I usually use python so I’ll do the same here. Those who don’t use python can just exit the page (I’m kidding, you might be angry and if you are so then you can just exit the page (I’m kidding, you mig….)).

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        window_sum = sum(nums[:k])
        max_sum = window_sum

        for i in range(k, len(nums)):
            window_sum += nums[i] - nums[i - k]
            max_sum = max(max_sum, window_sum)

        return max_sum / float(k)

Wait, no need to ask ChatGpt to explain the code. I’ve already done that and simplified it a bit more cuz ya’ll are dummies. So here’s the explaination:

  • I’m storing the maximum sum for each subarray in a variable called max_sum.

  • The window_sum calculates the sum of the first k elements of the given list/array.

  • Now to move (technically and stylistically slide) the subarray, we add the value of the next element to the window_sum and subtract the first element of the subarray from the window_sum. So the imaginary subarray is imaginarily sliding through the list/array. (We just add the values and don’t care about the subarray as the question just asks for the values and not the subarray plus we programmers are lazy af).

  • Now we replace the max_sum if the new window_sum is greater than the current one.

  • And finally we return their average.

Hurray! You guys solved your first problem using ‘The Sliding Window’!

Now do you get how did it get the name - Sliding Window? If you didn’t then go watch some reels idiot!

Where are you going already? I’m not done yet. We’ll solve another problem with this same technique. (Yes, I’m acting like an Asian father trying to teach his son maths on a random Sunday).

Problem 2. At this point ya’ll getting bored I know but this one’s interesting trust me.

So in this problem, you basically need to do kinda the same thing but instead of getting the maximum average of the subarrays you find the maximum number of vowels in a substring. Let’s look at the solution:

class Solution:
    def isVowel (self, c):
            return c in {'a', 'e', 'i', 'o', 'u'}

    def maxVowels(self, s: str, k: int) -> int:
        max_vowel = 0
        left = 0
        vowel = 0

        for right in range(len(s)):
            if self.isVowel(s[right]):
                vowel+=1
            if (right - left + 1) == k:
                max_vowel = max(max_vowel, vowel)
                if self.isVowel(s[left]):
                    vowel-=1
                left +=1

        return max_vowel

In this code we are implementing the following steps to make things more simple:

  • We have variables max_vowel, and vowel which we’ll compare and replace max_vowel if vowel is greater than max_vowel. Both of these variables store the count of vowel occurrences.

  • The left variable works as the extreme left index of the subarray.

  • The right index is actually the for loop variable so it’ll keep incrementing at each iteration. In order to make the window slide, we’ll just have to increment the left index variable.

And There you go, that’s sliding window for ya!

Now lemme go, it’s almost 4 a.m, my eyes are red but I don’t wanna sleep. Follow or do whatever you do in hashnode so that I can sleep today. (P.S this is my first hashnode blog)

BBye, happy coding!

0
Subscribe to my newsletter

Read articles from Sohom Roy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sohom Roy
Sohom Roy