 # Sliding Window

## Introduction

Sliding window is an optimization technique generally applied in problems involving arrays and strings. When applied correctly, it can reduce the time complexity of an algorithm by a factor of O(n). For example, it can be used to optimize algorithms time complexity from O(n^2) to O(n) or O(n^3) to O(n^2) etc. This is done by reusing the computation done for the previous window for the next window which eliminates the need of the inner for loop.  Please take a look at the example below to understand this further.

## Example

Let us go over an example to understand how we can optimize the runtime of any algorithm using sliding window technique.

Let’s say we are given an array A consisting of n positive integers, and a positive integer K. We need to print the sum of all the integers  for consecutive subarrays of size K. for example, if the given array is [1, 2, 3, 4, 5, 6] and K = 3, then I need to print the sum of following subarrays :

1. [1, 2, 3]

2. [2, 3, 4]

3. [3, 4, 5]

4. [4, 5, 6]

Using brute force approach, I can easily solve this problem using two nested for loops and going over the sum of the consecutive subarrays as shown below:

However, the above approach has a time complexity of O(nk) and in the worst case k = n and time complexity jumps to O(n^2). This technique can be optimized further by using sliding window technique.

Let us denote the sum of the first subarray (from index 0 till 2) as sum, sum of second subarray (from index 1 till 3) as sum and so on.

Clearly,

sum = arr + arr + arr

sum = arr + arr + arr

sum = arr + arr + arr

and so on.

We can eliminate the inner for loop in the brute force solution discussed above by rewriting the values of sum, sum in terms of it’s previous window/subarray as shown below. sum = sum – arr + arr

sum = sum – arr + arr

sum = sum – arr + arr

and so on.

Using the above approach, we can remove the inner for loop and reduce the time complexity from O(nk) to O(n). Take a look at the code given below.

## Hard

Scroll to Top

### Full Stack Integrated Bootcamp Free Trial

• Please enter a number from 7000000000 to 9999999999.