0% found this document useful (0 votes)
13 views

Sliding_Window_Technique_With_Code_Examples

The Sliding Window Technique is an efficient method for solving problems involving arrays, lists, or strings by maintaining a dynamic substructure that adjusts its size with two pointers. This technique optimizes time complexity from O(n²) to O(n) by avoiding redundant calculations, making it suitable for problems related to subarrays or substrings. Variations of the technique include fixed-size, variable-size, and sliding window with data structures like deques and hash maps, each tailored for specific problem requirements.

Uploaded by

gaurav.iitkgpian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Sliding_Window_Technique_With_Code_Examples

The Sliding Window Technique is an efficient method for solving problems involving arrays, lists, or strings by maintaining a dynamic substructure that adjusts its size with two pointers. This technique optimizes time complexity from O(n²) to O(n) by avoiding redundant calculations, making it suitable for problems related to subarrays or substrings. Variations of the technique include fixed-size, variable-size, and sliding window with data structures like deques and hash maps, each tailored for specific problem requirements.

Uploaded by

gaurav.iitkgpian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Sliding Window Technique: A

Comprehensive Guide
1. What is the Sliding Window Technique?

The sliding window technique is a powerful approach used to solve problems involving
arrays, lists, or strings. It is particularly useful for problems related to subarrays or
substrings. In essence, a sliding window refers to a dynamic substructure that moves across
the dataset, adjusting its size as required to solve the problem. The technique works by
maintaining a window defined by two pointers (start and end), which “slide” over the data.

The main advantage of this technique is that it avoids recalculating data within the window
from scratch, making it a time-efficient solution for many problems.

2. What Problem Does the Sliding Window Technique Solve?

Before the sliding window technique, brute-force solutions involved recalculating results
for every possible subarray or substring, leading to time complexities of O(n²) or worse.
This becomes inefficient for large datasets. The sliding window method optimizes such
problems by using O(n) time, where the window slides over the array while maintaining
a running result and eliminating redundant recalculations.

Example: Maximum Sum Subarray of Fixed Size (Brute-Force vs Sliding Window)

Problem: Find the maximum sum of any subarray of size k in an array arr.
Brute-Force Solution:
- Loop through every possible subarray of size k, calculate the sum, and keep track of the
maximum.
- Time Complexity: O(n * k)
Sliding Window Solution:
- Initialize a window of the first k elements, calculate the sum.
- Slide the window by adding the next element and subtracting the first element of the
previous window.
- Time Complexity: O(n)
Without Sliding Window: O(n * k)
With Sliding Window: O(n)

// Brute-force approach: O(n * k)

int maxSumSubarrayBruteForce(vector<int>& arr, int k) {


int n = arr.size();
int maxSum = INT_MIN;
for (int i = 0; i <= n - k; ++i) {
int currentSum = 0;
for (int j = i; j < i + k; ++j) {
currentSum += arr[j];
}
maxSum = max(maxSum, currentSum);
}
return maxSum;
}

// Sliding window approach: O(n)

int maxSumSubarraySlidingWindow(vector<int>& arr, int k) {


int n = arr.size();
int maxSum = 0, currentSum = 0;
for (int i = 0; i < k; ++i) {
currentSum += arr[i];
}
maxSum = currentSum;

for (int i = k; i < n; ++i) {


currentSum += arr[i] - arr[i - k];
maxSum = max(maxSum, currentSum);
}
return maxSum;
}

3. Identifying Sliding Window Problems

To recognize problems suitable for the sliding window approach, look for these keywords:
- Subarray or Substring
- Contiguous Elements
- Fixed or Variable Window Size
- Optimization requirements (e.g., time, space)

4. Variations of the Sliding Window Technique


The sliding window technique has several variations that can be applied depending on the
nature of the problem.
Below are the main variations, each with an example problem and a brief explanation of the
approach used.

1. Fixed-Size Sliding Window

Description: The size of the window remains constant as it slides over the array or string.
You typically use this for
problems where you are asked to examine every subarray or substring of a fixed size k.
Example Problem: Find the maximum sum of a subarray of size k.

2. Variable-Size Sliding Window

Description: The window’s size can expand or contract dynamically based on certain
conditions. This is useful for problems
where you need to find subarrays or substrings of varying lengths that satisfy specific
constraints.
Example Problem: Find the smallest subarray with a sum greater than or equal to a target
sum S.

3. Dynamic-Size Sliding Window (Two Pointers)

Description: Similar to variable-size sliding window, but both the start and end pointers are
moved dynamically.
Example Problem: Longest substring with at most k distinct characters.
4. Sliding Window with Deque (Monotonic Deque)

Description: In this variation, a deque (double-ended queue) is used to maintain a sliding


window of useful elements
(e.g., the maximum or minimum) in a way that allows efficient updating.
Example Problem: Sliding window maximum.

5. Sliding Window with HashMap/Set (Frequency Map)

Description: A sliding window that uses a hash map or set to track frequencies or unique
elements within the window.
Example Problem: Longest substring without repeating characters.

6. Nested Sliding Window

Description: This is a less common variation where one sliding window is nested within
another, often used for advanced
problems requiring multiple layers of iteration within a window.
Example Problem: Finding the number of distinct pairs of subarrays that meet certain
conditions.

7. Cyclic Sliding Window

Description: This variation is used when dealing with circular arrays or cyclic buffers,
where the end of the array wraps
around to the beginning.
Example Problem: Maximum sum in a circular subarray.

8. Sliding Window with Early Termination

Description: In this variation, the sliding window can terminate early when a solution is
found. It is an optimization
that reduces the number of iterations needed.
Example Problem: Smallest subarray with sum greater than or equal to S (early
termination).

5. Question Bank (Fixed Window Size, Variable Window Size)

Fixed Sliding Window:


1)https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/ (Leetcode
2461)
2)https://leetcode.com/problems/sliding-subarray-beauty/(Leetcode 2653)
3)https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/(Leetcode 1423)
4)https://leetcode.com/problems/maximum-average-subarray-i/(Leetcode 643)
5)https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-
equal-to-threshold/(Leetcode 1343)
6)https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/
(Leetcode 1461)
7)https://leetcode.com/problems/find-all-anagrams-in-a-string/(Leetcode 438)
8)https://leetcode.com/problems/permutation-in-string/(Leetcode 567)
9)https://leetcode.com/problems/sliding-window-maximum/(Leetcode 239)
10)https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/
description/(Leetcode 1876)

Variable Sized Sliding Window:


11)https://leetcode.com/problems/find-the-longest-semi-repetitive-substring/(Leetcode
2730)
12)https://leetcode.com/problems/count-the-number-of-good-subarrays/(Leetcode 2537)
13)https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/(Leetcode 2260)
14)https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/(Leetcode
1658)
15)https://leetcode.com/problems/count-number-of-nice-subarrays/(Leetcode 1248)
16)https://leetcode.com/problems/fruit-into-baskets/(Leetcode 904)
17)https://leetcode.com/problems/max-consecutive-ones-iii/(Leetcode 1004)
18)https://leetcode.com/problems/subarray-product-less-than-k/(Leetcode 713)
19)https://leetcode.com/problems/minimum-size-subarray-sum/(Leetcode 209)
20)https://leetcode.com/problems/longest-substring-without-repeating-characters/(Leetcode
3)

Here’s a comprehensive list of excellent sliding window problems:


https://leetcode.com/problem-list/sliding-window/

Code Examples for Variations:

1. Fixed-Size Sliding Window

// Sliding window approach to find the maximum sum of a subarray of fixed size k
int maxSumSubarraySlidingWindow(vector<int>& arr, int k) {
int n = arr.size();
int maxSum = 0, currentSum = 0;
for (int i = 0; i < k; ++i) {
currentSum += arr[i];
}
maxSum = currentSum;
for (int i = k; i < n; ++i) {
currentSum += arr[i] - arr[i - k];
maxSum = max(maxSum, currentSum);
}
return maxSum;
}

2. Variable-Size Sliding Window

// Sliding window approach to find the smallest subarray with sum >= target
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size();
int minLength = INT_MAX, currentSum = 0, start = 0;
for (int end = 0; end < n; ++end) {
currentSum += nums[end];
while (currentSum >= target) {
minLength = min(minLength, end - start + 1);
currentSum -= nums[start++];
}
}
return minLength == INT_MAX ? 0 : minLength;
}

3. Dynamic-Size Sliding Window (Two Pointers)

// Find the longest substring with at most k distinct characters


int lengthOfLongestSubstringKDistinct(string s, int k) {
unordered_map<char, int> charCount;
int start = 0, maxLength = 0;
for (int end = 0; end < s.length(); end++) {
charCount[s[end]]++;
while (charCount.size() > k) {
charCount[s[start]]--;
if (charCount[s[start]] == 0) charCount.erase(s[start]);
start++;
}
maxLength = max(maxLength, end - start + 1);
}
return maxLength;
}

4. Sliding Window with Deque (Monotonic Deque)

// Sliding window maximum using deque


vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
if (!dq.empty() && dq.front() == i - k) dq.pop_front();
while (!dq.empty() && nums[dq.back()] < nums[i]) dq.pop_back();
dq.push_back(i);
if (i >= k - 1) result.push_back(nums[dq.front()]);
}
return result;
}

5. Sliding Window with HashMap/Set (Frequency Map)

// Longest substring without repeating characters using HashSet


int lengthOfLongestSubstring(string s) {
unordered_set<char> charSet;
int start = 0, maxLength = 0;
for (int end = 0; end < s.length(); end++) {
while (charSet.find(s[end]) != charSet.end()) {
charSet.erase(s[start++]);
}
charSet.insert(s[end]);
maxLength = max(maxLength, end - start + 1);
}
return maxLength;
}

6. Nested Sliding Window

// Example problem using nested sliding windows (pseudo-code)


// Find pairs of subarrays that meet certain conditions
for (int start1 = 0; start1 < n; ++start1) {
for (int end1 = start1; end1 < n; ++end1) {
// First sliding window logic here (start1, end1)
for (int start2 = end1 + 1; start2 < n; ++start2) {
for (int end2 = start2; end2 < n; ++end2) {
// Second sliding window logic here (start2, end2)
// Check condition on subarrays (start1, end1) and (start2, end2)
}
}
}
}

7. Cyclic Sliding Window

// Maximum sum in a circular subarray


int maxSubarraySumCircular(vector<int>& A) {
int total = 0, maxSum = INT_MIN, minSum = INT_MAX;
int currMax = 0, currMin = 0;
for (int a : A) {
currMax = max(currMax + a, a);
maxSum = max(maxSum, currMax);
currMin = min(currMin + a, a);
minSum = min(minSum, currMin);
total += a;
}
return maxSum > 0 ? max(maxSum, total - minSum) : maxSum;
}

8. Sliding Window with Early Termination

// Sliding window with early termination for sum >= target


int minSubArrayLenEarlyTermination(int s, vector<int>& nums) {
int n = nums.size();
int start = 0, sum = 0, minLength = INT_MAX;
for (int end = 0; end < n; ++end) {
sum += nums[end];
while (sum >= s) {
minLength = min(minLength, end - start + 1);
sum -= nums[start++];
}
}
return minLength == INT_MAX ? 0 : minLength;
}
Article on Sliding Window Technique By:

Name: GAURAV BHARDWAJ

Email: [email protected]

Linked in: https://www.linkedin.com/in/gaurav-bhardwaj-5475b022a/

You might also like