Window Sliding Technique in C
Loops are part of almost every complex problem. Too many loops/ nested loops increase the required time, thus increasing the time complexity of the program. The window sliding technique is one of the computation techniques used to reduce the number of nested loops used in a program by replacing a nested loop with a single loop to increase the program's efficiency.
This technique is similar if you are familiar with the Sliding window protocol in computer networks. This tutorial explains how this technique is used with different examples.
Generally, when we use a nested loop like this:
The outer loop is executed n times; every time the outer loop executes, the inner loop is executed for (k-i) several times. The average time required to execute the whole loop would be approximately O(N2). Hence, developers don't suggest using loops.
Let us take an example to understand the concept clearly:
Suppose we're supposed to find the maximum sum of 'k' consecutive elements in an array. The user will provide the value of k.
First, if we use the na´ve approach, for every element i in the array, we'll iterate the array from i + 1 till n - 1 where n is the size of the array. We need to do this for every element and compare the sums to get the maximum sum.
Na´ve Brute force method:
Enter the size of the array: 7 Enter the elements of the array: 9 2 7 9 4 2 8 Enter the size of the sub-array: 3 The maximum sum of 3 consecutive elements of the array: 20
Now, here comes the sliding window technique:
The concept here is that we create a window of size k, and we'll keep sliding it by a unit index. Here, the window isn't any technical term. Rather than using a single value as we do in loops, we use multiple elements simultaneously in each iteration.
Given an array of size 10:
Suppose we need the maximum sum of 3 consecutive indexes, create a 3-sized window, and keep sliding (traversing) it throughout the array. Here is a pictorial representation:
Here is the code:
Enter the size of the array: 10 Enter the elements: 8 2 1 7 3 2 5 8 1 3 Enter the value of k: 3 The maximum sum of 3 consecutive elements in the array: 15
Here are the steps to apply the technique to any problem at hand: