Window Sliding Technique is a computational technique that aims to reduce the use of nested loops and replace it with a single loop, thereby reducing the time complexity.
What is a Sliding Window?
Consider a long chain connected together. Suppose you want to apply oil in the complete chain with your hands, without pouring the oil from above.
One way to do so is to:
- pick some oil,
- apply onto a section of the chain,
- then again pick some oil
- then apply it to the next section where oil is not applied yet
- and so on till the complete chain is oiled.
Another way to do so is to use a cloth, dip it in oil, and then hold onto one end of the chain with this cloth. Then instead of re-dipping it again and again, just slide the cloth with your hand onto the next section, and next, and so on till the other end.
The second way is known as the Sliding window technique and the portion which is slid from one end to end is known as Sliding Window.

Sliding window technique
Prerequisite to use the Sliding window technique
The use of the Sliding Window technique can be done in a very specific scenario, where the size of the window for computation is fixed throughout the complete nested loop. Only then the time complexity can be reduced.
How to use Sliding Window Technique?
The general use of the Sliding window technique can be demonstrated as follows:
- Find the size of the window required
- Compute the result for 1st window, i.e. from the start of the data structure
- Then use a loop to slide the window by 1, and keep computing the result window by window.
How to Know, Where we use the Sliding Window?
To know, Where we use the Sliding Window then we remember the following terms which is mentioned below:
Array, String, Sub Array, Sub String, Largest Sum, Maximum Sum, Minimum Sum
So, These terms help you to know where you have to use the sliding window.
Examples to illustrate the use of the Sliding window technique
Example: Given an array of integers of size ‘n’, Our aim is to calculate the maximum sum of ‘k’ consecutive elements in the array.
Input : arr[] = {100, 200, 300, 400}, k = 2
Output : 700
Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4
Output : 39
We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.
Input : arr[] = {2, 3}, k = 3
Output : Invalid
There is no subarray of size 3 as size of whole array is 2.
Naive Approach: So, let’s analyze the problem with Brute Force Approach. We start with the first index and sum till the kth element. We do it for all possible consecutive blocks or groups of k elements. This method requires a nested for loop, the outer for loop starts with the starting element of the block of k elements, and the inner or the nested loop will add up till the kth element.
Consider the below implementation :
C++
#include <bits/stdc++.h>
using namespace std;
int maxSum( int arr[], int n, int k)
{
int max_sum = INT_MIN;
for ( int i = 0; i < n - k + 1; i++) {
int current_sum = 0;
for ( int j = 0; j < k; j++)
current_sum = current_sum + arr[i + j];
max_sum = max(current_sum, max_sum);
}
return max_sum;
}
int main()
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxSum(arr, n, k);
return 0;
}
|
C
#include <limits.h>
#include <math.h>
#include <stdio.h>
int max( int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
int maxSum( int arr[], int n, int k)
{
int max_sum = INT_MIN;
for ( int i = 0; i < n - k + 1; i++) {
int current_sum = 0;
for ( int j = 0; j < k; j++)
current_sum = current_sum + arr[i + j];
max_sum = max(current_sum, max_sum);
}
return max_sum;
}
int main()
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , maxSum(arr, n, k));
return 0;
}
|
Java
class GFG {
static int maxSum( int arr[], int n, int k)
{
int max_sum = Integer.MIN_VALUE;
for ( int i = 0 ; i < n - k + 1 ; i++) {
int current_sum = 0 ;
for ( int j = 0 ; j < k; j++)
current_sum = current_sum + arr[i + j];
max_sum = Math.max(current_sum, max_sum);
}
return max_sum;
}
public static void main(String[] args)
{
int arr[] = { 1 , 4 , 2 , 10 , 2 , 3 , 1 , 0 , 20 };
int k = 4 ;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}
|
Python3
import sys
INT_MIN = - sys.maxsize - 1
def maxSum(arr, n, k):
max_sum = INT_MIN
for i in range (n - k + 1 ):
current_sum = 0
for j in range (k):
current_sum = current_sum + arr[i + j]
max_sum = max (current_sum, max_sum)
return max_sum
arr = [ 1 , 4 , 2 , 10 , 2 ,
3 , 1 , 0 , 20 ]
k = 4
n = len (arr)
print (maxSum(arr, n, k))
|
C#
using System;
class GFG {
static int maxSum( int [] arr, int n, int k)
{
int max_sum = int .MinValue;
for ( int i = 0; i < n - k + 1; i++) {
int current_sum = 0;
for ( int j = 0; j < k; j++)
current_sum = current_sum + arr[i + j];
max_sum = Math.Max(current_sum, max_sum);
}
return max_sum;
}
public static void Main()
{
int [] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.Length;
Console.WriteLine(maxSum(arr, n, k));
}
}
|
PHP
<?php
?>
<?php
function maxSum( $arr , $n , $k )
{
$max_sum = PHP_INT_MIN ;
for ( $i = 0; $i < $n - $k + 1; $i ++)
{
$current_sum = 0;
for ( $j = 0; $j < $k ; $j ++)
$current_sum = $current_sum +
$arr [ $i + $j ];
$max_sum = max( $current_sum , $max_sum );
}
return $max_sum ;
}
$arr = array (1, 4, 2, 10, 2, 3, 1, 0, 20);
$k = 4;
$n = count ( $arr );
echo maxSum( $arr , $n , $k );
?>
|
Javascript
<script>
function maxSum( arr, n, k){
let max_sum = 0;
for (let i = 0; i < K; i++){
max_sum += Arr[i];
}
let window_sum = max_sum;
for (let i = K; i < N; i++){
window_sum = window_sum - Arr[i-K] + Arr[i];
max_sum = Math.max(max_sum,window_sum);
}
return max_sum
}
let arr = [ 1, 4, 2, 10, 2, 3, 1, 0, 20 ];
let k = 4;
let n = arr.length;
document.write(maxSum(arr, n, k));
</script>
|
Time complexity: O(k*n) as it contains two nested loops.
Auxiliary Space: O(1)
Sliding Window Technique: The technique can be best understood with the window pane in the bus, considering a window of length n and the pane which is fixed in it of length k. Consider, initially the pane is at extreme left i.e., at 0 units from the left. Now, co-relate the window with array arr[] of size n and pane with current_sum of size k elements. Now, if we apply force on the window, it moves a unit distance ahead. The pane will cover the next k consecutive elements.
Applying the sliding window technique :
- We compute the sum of the first k elements out of n terms using a linear loop and store the sum in variable window_sum.
- Then we will graze linearly over the array till it reaches the end and simultaneously keep track of the maximum sum.
- To get the current sum of a block of k elements just subtract the first element from the previous block and add the last element of the current block.
The below representation will make it clear how the window slides over the array.
Consider an array arr[] = {5, 2, -1, 0, 3} and value of k = 3 and n = 5
This is the initial phase where we have calculated the initial window sum starting from index 0 . At this stage the window sum is 6. Now, we set the maximum_sum as current_window i.e 6.

Now, we slide our window by a unit index. Therefore, now it discards 5 from the window and adds 0 to the window. Hence, we will get our new window sum by subtracting 5 and then adding 0 to it. So, our window sum now becomes 1. Now, we will compare this window sum with the maximum_sum. As it is smaller, we wont change the maximum_sum.

Similarly, now once again we slide our window by a unit index and obtain the new window sum to be 2. Again we check if this current window sum is greater than the maximum_sum till now. Once, again it is smaller so we don’t change the maximum_sum.
Therefore, for the above array our maximum_sum is 6.

Below is the code for above approach:
C++
#include <iostream>
using namespace std;
int maxSum( int arr[], int n, int k)
{
if (n < k) {
cout << "Invalid" ;
return -1;
}
int max_sum = 0;
for ( int i = 0; i < k; i++)
max_sum += arr[i];
int window_sum = max_sum;
for ( int i = k; i < n; i++) {
window_sum += arr[i] - arr[i - k];
max_sum = max(max_sum, window_sum);
}
return max_sum;
}
int main()
{
int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxSum(arr, n, k);
return 0;
}
|
Java
class GFG {
static int maxSum( int arr[], int n, int k)
{
if (n < k) {
System.out.println( "Invalid" );
return - 1 ;
}
int max_sum = 0 ;
for ( int i = 0 ; i < k; i++)
max_sum += arr[i];
int window_sum = max_sum;
for ( int i = k; i < n; i++) {
window_sum += arr[i] - arr[i - k];
max_sum = Math.max(max_sum, window_sum);
}
return max_sum;
}
public static void main(String[] args)
{
int arr[] = { 1 , 4 , 2 , 10 , 2 , 3 , 1 , 0 , 20 };
int k = 4 ;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}
|
Python3
def maxSum(arr, k):
n = len (arr)
if n < k:
print ( "Invalid" )
return - 1
window_sum = sum (arr[:k])
max_sum = window_sum
for i in range (n - k):
window_sum = window_sum - arr[i] + arr[i + k]
max_sum = max (window_sum, max_sum)
return max_sum
arr = [ 1 , 4 , 2 , 10 , 2 , 3 , 1 , 0 , 20 ]
k = 4
print (maxSum(arr, k))
|
C#
using System;
class GFG {
static int maxSum( int [] arr, int n, int k)
{
if (n < k) {
Console.WriteLine( "Invalid" );
return -1;
}
int max_sum = 0;
for ( int i = 0; i < k; i++)
max_sum += arr[i];
int window_sum = max_sum;
for ( int i = k; i < n; i++) {
window_sum += arr[i] - arr[i - k];
max_sum = Math.Max(max_sum, window_sum);
}
return max_sum;
}
public static void Main()
{
int [] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
int n = arr.Length;
Console.WriteLine(maxSum(arr, n, k));
}
}
|
PHP
<?php
function maxSum( $arr , $n , $k )
{
if ( $n < $k )
{
echo "Invalid" ;
return -1;
}
$max_sum = 0;
for ( $i = 0; $i < $k ; $i ++)
$max_sum += $arr [ $i ];
$window_sum = $max_sum ;
for ( $i = $k ; $i < $n ; $i ++)
{
$window_sum += $arr [ $i ] - $arr [ $i - $k ];
$max_sum = max( $max_sum , $window_sum );
}
return $max_sum ;
}
$arr = array (1, 4, 2, 10, 2, 3, 1, 0, 20);
$k = 4;
$n = count ( $arr );
echo maxSum( $arr , $n , $k );
?>
|
Javascript
<script>
function maxSum(arr, n, k) {
let max = 0;
let sum = 0;
for (let i = 0; i < k; i++) {
sum += arr[i];
max = sum;
}
for (let i = k; i < n; i++) {
sum += arr[i] - arr[i - k];
if (sum > max) {
max = sum;
}
}
return max;
}
let arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
let k = 4;
let n = arr.length;
document.write(maxSum(arr, n, k));
</script>
|
Now, it is quite obvious that the Time Complexity is linear as we can see that only one loop runs in our code. Hence, our Time Complexity is O(n).
We can use this technique to find max/min k-subarray, XOR, product, sum, etc. Refer to sliding window problems for such problems.
This article is contributed by Kanika Thakral. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.