Sliding_Window_Technique_With_Code_Examples
Sliding_Window_Technique_With_Code_Examples
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.
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.
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)
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)
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.
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.
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: 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.
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.
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.
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).
// 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;
}
// 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;
}
Email: [email protected]