The Sliding Window is a powerful algorithmic technique used to optimize problems involving arrays or strings. It helps reduce the time complexity of problems that require checking or computing results over contiguous subarrays or substrings.
Instead of repeatedly iterating over the same elements, the sliding window maintains a range (or “window”) that moves step-by-step through the data, updating results incrementally.
When to Use Sliding Window
You can apply the sliding window technique when:
The problem involves a contiguous sequence (subarray or substring).
You need to find: => Maximum/Minimum sum in a fixed-size window. => Longest/Shortest subarray with certain conditions. => Count of distinct elements in a range.
Brute force would involve nested loops, leading to higher complexity.
Example Problem - Maximum Sum of a Subarray with K Elements
Given an array arr[] and an integer k, we need to calculate the maximum sum of a subarray having size exactly k.
Input : arr[] = [5, 2, -1, 0, 3], k = 3 Output : 6 Explanation : We get maximum sum by considering the subarray [300, 400]
Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39 Explanation : We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.
Naive Approach - O(n×k) Time and O(1) Space
C++
#include<iostream>#include<vector>#include<climits>usingnamespacestd;intmaxSum(vector<int>&arr,intk){intn=arr.size();intmax_sum=INT_MIN;// Consider all blocks starting with ifor(inti=0;i<=n-k;i++){intcurrent_sum=0;// Calculate sum of current subarray of size kfor(intj=0;j<k;j++)current_sum+=arr[i+j];// Update result if requiredmax_sum=max(current_sum,max_sum);}returnmax_sum;}intmain(){vector<int>arr={5,2,-1,0,3};intk=3;cout<<maxSum(arr,k)<<endl;return0;}
#include <iostream>
#include <vector>
#include <climits>
usingnamespacestd;
intmaxSum(vector<int>&arr, intk) {
intn=arr.size();
intmax_sum=INT_MIN;
// Consider all blocks starting with i
for (inti=0; i<=n-k; i++) {
intcurrent_sum=0;
// Calculate sum of current subarray of size k
for (intj=0; j<k; j++)
current_sum+=arr[i+j];
// Update result if required
max_sum=max(current_sum, max_sum);
}
returnmax_sum;
}
intmain() {
vector<int>arr= {5, 2, -1, 0, 3};
intk=3;
cout<<maxSum(arr, k) <<endl;
return0;
}
C
#include<limits.h>#include<math.h>#include<stdio.h>// Find maximum between two numbers.intmax(intnum1,intnum2){return(num1>num2)?num1:num2;}intmaxSum(intarr[],intn,intk){// Initialize resultintmax_sum=INT_MIN;// Consider all blocks starting with i.for(inti=0;i<n-k+1;i++){intcurrent_sum=0;for(intj=0;j<k;j++)current_sum=current_sum+arr[i+j];// Update result if required.max_sum=max(current_sum,max_sum);}returnmax_sum;}// Driver codeintmain(){intarr[]={5,2,-1,0,3};intk=3;intn=sizeof(arr)/sizeof(arr[0]);printf("%d",maxSum(arr,n,k));return0;}
Java
classGFG{// Returns maximum sum in// a subarray of size k.staticintmaxSum(intarr[],intn,intk){// Initialize resultintmax_sum=Integer.MIN_VALUE;// Consider all blocks starting with i.for(inti=0;i<n-k+1;i++){intcurrent_sum=0;for(intj=0;j<k;j++)current_sum=current_sum+arr[i+j];// Update result if required.max_sum=Math.max(current_sum,max_sum);}returnmax_sum;}publicstaticvoidmain(String[]args){intarr[]={5,2,-1,0,3};intk=3;intn=arr.length;System.out.println(maxSum(arr,n,k));}}
Python
importsysdefmaxSum(arr,n,k):# Initialize resultmax_sum=-sys.maxsize# Consider all blocks starting with i.foriinrange(n-k+1):current_sum=0forjinrange(k):current_sum+=arr[i+j]# Update result if required.max_sum=max(current_sum,max_sum)returnmax_sumif__name__=="__main__":arr=[5,2,-1,0,3]k=3n=len(arr)print(maxSum(arr,n,k))
C#
usingSystem;classGFG{// Returns maximum sum in a// subarray of size k.staticintmaxSum(int[]arr,intn,intk){// Initialize resultintmax_sum=int.MinValue;// Consider all blocks starting// with i.for(inti=0;i<n-k+1;i++){intcurrent_sum=0;for(intj=0;j<k;j++)current_sum=current_sum+arr[i+j];// Update result if required.max_sum=Math.Max(current_sum,max_sum);}returnmax_sum;}publicstaticvoidMain(){int[]arr={5,2,-1,0,3};intk=3;intn=arr.Length;Console.WriteLine(maxSum(arr,n,k));}}
JavaScript
functionmaxSum(arr,n,k){// Initialize resultletmax_sum=Number.MIN_SAFE_INTEGER;// Consider all blocks starting with ifor(leti=0;i<n-k+1;i++){letcurrent_sum=0;for(letj=0;j<k;j++){current_sum+=arr[i+j];}// Update result if requiredmax_sum=Math.max(current_sum,max_sum);}returnmax_sum;}// Driver codeconstarr=[5,2,-1,0,3];constk=3;constn=arr.length;console.log(maxSum(arr,n,k));
Output
6
Using the Sliding Window Technique - O(n) Time and O(1) Space
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 traverse 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 won't 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.
C++
#include<iostream>#include<vector>usingnamespacestd;intmaxSum(vector<int>&arr,intk){intn=arr.size();// n must be greaterif(n<=k){cout<<"Invalid";return-1;}// Compute sum of first window of size kintmax_sum=0;for(inti=0;i<k;i++)max_sum+=arr[i];// Compute sums of remaining windows by// removing first element of previous// window and adding last element of// current window.intwindow_sum=max_sum;for(inti=k;i<n;i++){window_sum+=arr[i]-arr[i-k];max_sum=max(max_sum,window_sum);}returnmax_sum;}intmain(){vector<int>arr={5,2,-1,0,3};intk=3;cout<<maxSum(arr,k);return0;}
#include <iostream>
#include <vector>
usingnamespacestd;
intmaxSum(vector<int>&arr, intk){
intn=arr.size();
// n must be greater
if (n<=k) {
cout<<"Invalid";
return-1;
}
// Compute sum of first window of size k
intmax_sum=0;
for (inti=0; i<k; i++)
max_sum+=arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
intwindow_sum=max_sum;
for (inti=k; i<n; i++) {
window_sum+=arr[i] -arr[i-k];
max_sum=max(max_sum, window_sum);
}
returnmax_sum;
}
intmain(){
vector<int>arr= {5, 2, -1, 0, 3};
intk=3;
cout<<maxSum(arr, k);
return0;
}
Java
classGFG{staticintmaxSum(intarr[],intn,intk){// n must be greaterif(n<=k){System.out.println("Invalid");return-1;}// Compute sum of first window of size kintmax_sum=0;for(inti=0;i<k;i++)max_sum+=arr[i];// Compute sums of remaining windows by// removing first element of previous// window and adding last element of// current window.intwindow_sum=max_sum;for(inti=k;i<n;i++){window_sum+=arr[i]-arr[i-k];max_sum=Math.max(max_sum,window_sum);}returnmax_sum;}publicstaticvoidmain(String[]args){intarr[]={5,2,-1,0,3};intk=3;intn=arr.length;System.out.println(maxSum(arr,n,k));}}
Python
defmaxSum(arr,k):# length of the arrayn=len(arr)# n must be greater than kifn<=k:print("Invalid")return-1# Compute sum of first window of size kwindow_sum=sum(arr[:k])# first sum availablemax_sum=window_sum# Compute the sums of remaining windows by# removing first element of previous# window and adding last element of# the current window.foriinrange(n-k):window_sum=window_sum-arr[i]+arr[i+k]max_sum=max(window_sum,max_sum)returnmax_sumif__name__=="__main__":arr=[5,2,-1,0,3]k=3print(maxSum(arr,k))
C#
usingSystem;classGFG{staticintmaxSum(int[]arr,intn,intk){// n must be greaterif(n<=k){Console.WriteLine("Invalid");return-1;}// Compute sum of first window of size kintmax_sum=0;for(inti=0;i<k;i++)max_sum+=arr[i];// Compute sums of remaining windows by// removing first element of previous// window and adding last element of// current window.intwindow_sum=max_sum;for(inti=k;i<n;i++){window_sum+=arr[i]-arr[i-k];max_sum=Math.Max(max_sum,window_sum);}returnmax_sum;}publicstaticvoidMain(){int[]arr={5,2,-1,0,3};intk=3;intn=arr.Length;Console.WriteLine(maxSum(arr,n,k));}}
JavaScript
functionmaxSum(arr,k){constn=arr.length;if(n<k){console.log("Invalid");return-1;}// Compute sum of first window of size kletwindowSum=0;for(leti=0;i<k;i++){windowSum+=arr[i];}letmaxSum=windowSum;// Slide the window from start to end of the arrayfor(leti=k;i<n;i++){windowSum+=arr[i]-arr[i-k];maxSum=Math.max(maxSum,windowSum);}returnmaxSum;}// Driver Codeconstarr=[5,2,-1,0,3];constk=3;console.log(maxSum(arr,k));
Output
6
How to use Sliding Window Technique?
There are basically two types of sliding window:
1. Fixed Size Sliding Window:
The general steps to solve these questions by following below steps:
Find the size of the window required, say K.
Compute the result for 1st window, i.e. include the first K elements of the data structure.
Then use a loop to slide the window by 1 and keep computing the result window by window.
2. Variable Size Sliding Window:
The general steps to solve these questions by following below steps:
In this type of sliding window problem, we increase our right pointer one by one till our condition is true.
At any step if our condition does not match, we shrink the size of our window by increasing left pointer.
Again, when our condition satisfies, we start increasing the right pointer and follow step 1.
We follow these steps until we reach to the end of the array.
How to Identify Sliding Window Problems?
These problems generally require Finding Maximum/Minimum Subarray, Substrings which satisfy some specific condition.
The size of the subarray or substring ‘k’ will be given in some of the problems.
These problems can easily be solved in O(n2) time complexity using nested loops, using sliding window we can solve these in O(n) Time Complexity.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.