Sliding Window Technique is a method used to solve problems that involve subarray or substring or window.
- The main idea is to use the results of previous window to do computations for the next window.
- This technique is commonly used in algorithms like finding subarrays with a specific sum, finding the longest substring with unique characters, or solving problems that require a fixed-size window to process elements efficiently.
Example Problem - Maximum Sum of a Subarray with K Elements
Given an array and an integer k, we need to calculate the maximum sum of a subarray having size exactly k.
Input : arr[] = {100, 200, 300, 400}, k = 2
Output : 700
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
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 - O(n k) Time and O(1) Space
We run two nest loops and compute sums of all subarrays of size k
C++
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Returns maximum sum in a subarray of size k.
int maxSum(vector<int>& arr, int k) {
int n = arr.size();
int max_sum = INT_MIN;
// Consider all blocks starting with i
for (int i = 0; i <= n - k; i++) {
int current_sum = 0;
// Calculate sum of current subarray of size k
for (int j = 0; j < k; j++)
current_sum += arr[i + j];
// Update result if required
max_sum = max(current_sum, max_sum);
}
return max_sum;
}
// Driver code
int main() {
vector<int> arr = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int k = 4;
cout << maxSum(arr, k) << endl;
return 0;
}
C
// O(n*k) solution for finding maximum sum of
// a subarray of size k
#include <limits.h>
#include <math.h>
#include <stdio.h>
// Find maximum between two numbers.
int max(int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
// Returns maximum sum in a subarray of size k.
int maxSum(int arr[], int n, int k)
{
// Initialize result
int max_sum = INT_MIN;
// Consider all blocks starting with i.
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];
// Update result if required.
max_sum = max(current_sum, max_sum);
}
return max_sum;
}
// Driver code
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;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java code O(n*k) solution for finding maximum sum of
// a subarray of size k
class GFG {
// Returns maximum sum in
// a subarray of size k.
static int maxSum(int arr[], int n, int k)
{
// Initialize result
int max_sum = Integer.MIN_VALUE;
// Consider all blocks starting with i.
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];
// Update result if required.
max_sum = Math.max(current_sum, max_sum);
}
return max_sum;
}
// Driver code
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));
}
}
Python
import sys
# O(n * k) solution for finding
# maximum sum of a subarray of size k
# Returns maximum sum in a
# subarray of size k.
def maxSum(arr, n, k):
# Initialize result
max_sum = -sys.maxsize
# Consider all blocks
# starting with i.
for i in range(n - k + 1):
current_sum = 0
for j in range(k):
current_sum = current_sum + arr[i + j]
# Update result if required.
max_sum = max(current_sum, max_sum)
return max_sum
# Driver code
arr = [1, 4, 2, 10, 2,
3, 1, 0, 20]
k = 4
n = len(arr)
print(maxSum(arr, n, k))
C#
// C# code here O(n*k) solution for
// finding maximum sum of a subarray
// of size k
using System;
class GFG {
// Returns maximum sum in a
// subarray of size k.
static int maxSum(int[] arr, int n, int k)
{
// Initialize result
int max_sum = int.MinValue;
// Consider all blocks starting
// with i.
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];
// Update result if required.
max_sum = Math.Max(current_sum, max_sum);
}
return max_sum;
}
// Driver code
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));
}
}
JavaScript
// Function to find the maximum sum of a subarray of size k
function maxSum(arr, n, k) {
// Initialize result
let max_sum = Number.MIN_SAFE_INTEGER;
// Consider all blocks starting with i
for (let i = 0; i < n - k + 1; i++) {
let current_sum = 0;
for (let j = 0; j < k; j++) {
current_sum += arr[i + j];
}
// Update result if required
max_sum = Math.max(current_sum, max_sum);
}
return max_sum;
}
// Driver code
const arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
const k = 4;
const n = arr.length;
console.log(maxSum(arr, n, k));
PHP
<?php
// code
?>
<?php
// O(n*k) solution for finding maximum sum of
// a subarray of size k
// Returns maximum sum in a subarray of size k.
function maxSum($arr, $n, $k)
{
// Initialize result
$max_sum = PHP_INT_MIN ;
// Consider all blocks
// starting with i.
for ( $i = 0; $i < $n - $k + 1; $i++)
{
$current_sum = 0;
for ( $j = 0; $j < $k; $j++)
$current_sum = $current_sum +
gold $arr[$i + $j];
// Update result if required.
$max_sum = max($current_sum, $max_sum );
}
return $max_sum;
}
// Driver code
$arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20);
$k = 4;
$n = count($arr);
echo maxSum($arr, $n, $k);
?>
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.

Below is the code for above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Returns maximum sum in a subarray of size k.
int maxSum(vector<int>& arr, int k)
{
int n = arr.size();
// n must be greater
if (n <= k) {
cout << "Invalid";
return -1;
}
// Compute sum of first window of size k
int max_sum = 0;
for (int i = 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.
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;
}
// Driver code
int main()
{
vector<int> arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 };
int k = 4;
cout << maxSum(arr, k);
return 0;
}
Java
// Java code for
// O(n) solution for finding
// maximum sum of a subarray
// of size k
class GFG {
// Returns maximum sum in
// a subarray of size k.
static int maxSum(int arr[], int n, int k)
{
// n must be greater
if (n <= k) {
System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
int max_sum = 0;
for (int i = 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.
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;
}
// Driver code
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));
}
}
Python
# O(n) solution for finding
# maximum sum of a subarray of size k
def maxSum(arr, k):
# length of the array
n = len(arr)
# n must be greater than k
if n <= k:
print("Invalid")
return -1
# Compute sum of first window of size k
window_sum = sum(arr[:k])
# first sum available
max_sum = window_sum
# Compute the sums of remaining windows by
# removing first element of previous
# window and adding last element of
# the current window.
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
# Driver code
arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
k = 4
print(maxSum(arr, k))
C#
// C# code for O(n) solution for finding
// maximum sum of a subarray of size k
using System;
class GFG {
// Returns maximum sum in
// a subarray of size k.
static int maxSum(int[] arr, int n, int k)
{
// n must be greater
if (n <= k) {
Console.WriteLine("Invalid");
return -1;
}
// Compute sum of first window of size k
int max_sum = 0;
for (int i = 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.
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;
}
// Driver code
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));
}
}
// This code is contributed by anuj_67.
JavaScript
function maxSum(arr, k) {
const n = arr.length;
if (n < k) {
console.log("Invalid");
return -1;
}
// Compute sum of first window of size k
let windowSum = 0;
for (let i = 0; i < k; i++) {
windowSum += arr[i];
}
let maxSum = windowSum;
// Slide the window from start to end of the array
for (let i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
// Example usage
const arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
const k = 4;
console.log(maxSum(arr, k)); // Output: 24
PHP
<?php
// O(n) solution for finding maximum sum of
// a subarray of size k
// Returns maximum sum in a
// subarray of size k.
function maxSum( $arr, $n, $k)
{
// n must be greater
if ($n <= $k)
{
echo "Invalid";
return -1;
}
// Compute sum of first
// window of size k
$max_sum = 0;
for($i = 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.
$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;
}
// Driver code
$arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20);
$k = 4;
$n = count($arr);
echo maxSum($arr, $n, $k);
// This code is contributed by anuj_67
?>
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.
- Required Time Complexity: O(n) or O(n log n)
- Constraints: n <= 106
More Example Problems
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem