๐Ÿš€ Mastering the Sliding Window Technique in C++: Crack DSA Like a Pro!

Why & How!

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)):

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

cppCopyEditint 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

1. ๐Ÿ”ฅ Maximum Sum Subarray of Size K

2. ๐ŸŽ Fruit Into Baskets

3. ๐Ÿฅ‡ Longest Subarray of 1s After Deleting One Element

4. ๐Ÿงฎ Count Number of Nice Subarrays

5. ๐Ÿ’ผ 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):

cppCopyEditint 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!


๐Ÿง  Final Thoughts

Sliding Window is not just a pattern โ€” itโ€™s a mindset that helps you write better, faster, and cleaner code. Mastering it will make you more confident in coding interviews and more efficient in solving real-world data problems.

Stay sharp and keep coding ๐Ÿ’ป๐Ÿ”ฅ


0
Subscribe to my newsletter

Read articles from Muhammad Umair Ullah directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Muhammad Umair Ullah
Muhammad Umair Ullah