Javatpoint Logo
Javatpoint Logo

Sliding Window Algorithm in C++

The Sliding Window Technique is a computational method that intends to replace nested loops with a single loop, which reduce time complexity.

Sliding Window Technique

Let's use an analogy to help us comprehend this strategy. Consider a pane that is fixed inside a window that is length n and length k.

Combine the n-element array arr[] in the window with the k-element current sum in the pane while it is in its starting position, which is 0 units to the left. The window will move a unit distance if we push on it. The pane will cover the following k components.

Examples of how to apply the sliding window technique

Example:

Given an array of integers of size "n", our goal is to get the highest sum of the array's first "k" members.


We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.

There is no subarray of size 3 as size of whole array is 2.

Naive Approach:

Let's now analyse the problem using the Brute Force Approach. We increase up to the kth element starting with the first index. Each group of k items or blocks that can follow one another gets this done. The inner or nested loop of this method's nested for loops will add till the k-th element. The first item in the block of k items is where the outer for loop begins.

Think about the following application:

Output

34

As can be seen from the code above, which has two nested loops, the time complexity is O(k*n).

Consider a window with a length of n and a pane that is fixed in it with a length of k to better understand the sliding window technique. Take into account that the pane is originally at the very left, or 0 units from the left. Now, relate the window to the n-element array arr[] and the pane to the k-element current sum. If we now exert force on the window, it will move a unit of distance forward. The following k components will be covered by the pane.

Using the sliding window method

We use a linear loop to calculate the sum of the first k terms out of n, and we store the result in the variable window sum. Then, while simultaneously keeping track of the largest sum, we shall linearly graze across the array until it reaches its end.

Simply add the last element of the current block to the first element of the preceding block to obtain the current total of the block of k items.

The window moves over the array as shown in the example below.

Output

34

Now that we can see that our code only has one loop, it is clear that the Time Complexity is linear. Therefore, the Time Complexity is O(n).







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA