๐ Mastering the Sliding Window Technique in C++: Crack DSA Like a Pro!
When you're tackling arrays or strings in competitive programming or coding interviews, efficiency is king. Thatโs where the Sliding Window technique comes in โ a game-changing approach that helps you move from brute-force to optimized solutions.
In this guide, weโll dive deep into:
- ๐ก What is Sliding Window?
- ๐ง Why use it?
- ๐งฑ Brute Force vs Optimized Approaches
- ๐ Time & Space Complexities
- ๐งช Real-world Examples
- ๐ My GitHub Repository for Open Source Contribution
๐ง What is Sliding Window?
Sliding Window is a technique for solving problems involving linear data structures like arrays and strings. It involves creating a window (usually a subarray or substring) and moving it across the input to find a solution โ without recalculating everything inside the window.
๐ค The Brute Force Way (Naive Approach)
Problem Example:
Find the maximum sum of a subarray of size
k
.
Naive Approach (O(n*k)):
cpp
int maxSumBruteForce(vector<int>& nums, int k) {
int n = nums.size();
int maxSum = INT_MIN;
for (int i = 0; i <= n - k; i++) {
int sum = 0;
for (int j = 0; j < k; j++) {
sum += nums[i + j];
}
maxSum = max(maxSum, sum);
}
return maxSum;
}
Time Complexity: O(n*k)
Space Complexity: O(1)
๐ Optimized Sliding Window Approach
cpp
int maxSumSlidingWindow(vector<int>& nums, int k) {
int windowSum = 0, maxSum = INT_MIN;
for (int i = 0; i < k; i++) windowSum += nums[i];
maxSum = windowSum;
for (int i = k; i < nums.size(); i++) {
windowSum += nums[i] - nums[i - k];
maxSum = max(maxSum, windowSum);
}
return maxSum;
}
Time Complexity: O(n)
Space Complexity: O(1)
This approach avoids recalculating sums by adding the next element and removing the first element of the previous window.
๐งช Real Interview Examples Using Sliding Window
- ๐ฅ Maximum Sum Subarray of Size K
- ๐ Fruit Into Baskets
- ๐ฅ Longest Subarray of 1s After Deleting One Element
- ๐งฎ Count Number of Nice Subarrays
- ๐ผ Minimum Size Subarray Sum
๐ Use-Cases of Sliding Window
- Find the max/min/average of a subarray
- Count distinct elements in a subarray
- Longest substring with at most k distinct characters
- Smallest window that satisfies a condition
โ๏ธ Template Code (Variable-Size Window):
cpp
int solve(vector<int>& nums) {
int i = 0, j = 0, answer = 0;
unordered_map<int, int> freq;
while (j < nums.size()) {
freq[nums[j]]++;
// If condition violated
while (freq.size() > k) {
freq[nums[i]]--;
if (freq[nums[i]] == 0) freq.erase(nums[i]);
i++;
}
answer = max(answer, j - i + 1);
j++;
}
return answer;
}
๐จโ๐ป Open Source Contribution
All of my DSA solutions using Sliding Window (including the LeetCode/Striver/Nudecode-150 ones) are available in my GitHub repo:
๐ GitHub Repository:** ๐ Click Here to Explore My Solutions
Make sure to โญ star the repo and follow me for more updates!**
Top comments (0)