C++ Sliding Window Problems Made Simple

2025-08-05

Sliding window problems are some of the most common patterns in coding interviews. If you are preparing for LeetCode or other technical interviews, you’ll quickly notice how often this approach shows up. From subarray sums to string analysis, the sliding window is a must-know technique for anyone serious about C++ interviews.

In this post, I’ll break down the sliding window pattern step by step, give you simple C++ code examples, and show you how to think about it in interviews.


What is the sliding window technique?

The sliding window pattern is a way of solving problems by maintaining a “window” over part of your input (usually an array or string) and moving that window as you go. Instead of recalculating everything from scratch each time, you update your running state as the window expands or contracts.

The window can be:

  • Fixed size: The window always covers k elements (example: maximum sum of a subarray of length k).
  • Variable size: The window expands and shrinks depending on conditions (example: smallest substring containing all characters).

This reduces complexity from O(n^2) to O(n) in many cases.


Example 1: Maximum sum subarray of size k

Problem: Given an array of integers and a number k, find the maximum sum of any contiguous subarray of size k.

Brute force is O(n*k), but with a sliding window, we can do O(n).

#include <iostream>
#include <vector>
using namespace std;

int maxSumSubarray(const vector<int>& nums, int k) {
    int n = nums.size();
    int windowSum = 0, maxSum = 0;

    // First window
    for (int i = 0; i < k; i++) {
        windowSum += nums[i];
    }
    maxSum = windowSum;

    // Slide the window
    for (int i = k; i < n; i++) {
        windowSum += nums[i] - nums[i - k];
        maxSum = max(maxSum, windowSum);
    }

    return maxSum;
}

int main() {
    vector<int> nums = {2, 1, 5, 1, 3, 2};
    int k = 3;
    cout << maxSumSubarray(nums, k) << endl; // Output: 9
    return 0;
}

Here, the window keeps track of the sum. When we slide, we add the new element and subtract the element that left the window.


Example 2: Smallest substring with all distinct characters

Problem: Given a string, find the length of the smallest substring that contains all unique characters in the string.

This is a variable window problem.

#include <iostream>
#include <unordered_map>
using namespace std;

int smallestUniqueSubstring(const string& s) {
    unordered_map<char, int> freq;
    int left = 0, minLen = s.size();
    int uniqueCount = 0, required = 0;

    // Count how many distinct chars exist
    unordered_map<char, bool> distinct;
    for (char c : s) distinct[c] = true;
    required = distinct.size();

    for (int right = 0; right < s.size(); right++) {
        freq[s[right]]++;
        if (freq[s[right]] == 1) uniqueCount++;

        while (uniqueCount == required) {
            minLen = min(minLen, right - left + 1);
            freq[s[left]]--;
            if (freq[s[left]] == 0) uniqueCount--;
            left++;
        }
    }
    return minLen;
}

int main() {
    string s = "abca";
    cout << smallestUniqueSubstring(s) << endl; // Output: 3 ("abc")
    return 0;
}

The window grows until it contains all unique characters, then shrinks to find the minimum size that still satisfies the condition.


How to recognize sliding window problems

  1. The problem involves subarrays or substrings.
  2. The solution requires checking contiguous ranges of elements.
  3. There is a condition like "at most k", "exactly k", or "until all characters are included".
  4. The brute force solution looks like nested loops.

If you spot these patterns, sliding window is usually the right tool.


Common mistakes

  • Forgetting to update state correctly when shrinking the window.
  • Using extra space unnecessarily instead of maintaining counts.
  • Mixing up fixed vs variable window strategies.
  • Not handling edge cases (like window size larger than array size).

Practice problems on LeetCode

  • Maximum Average Subarray I
  • Longest Substring Without Repeating Characters
  • Minimum Window Substring
  • Fruit Into Baskets

Solving these will make you fluent in spotting and applying the pattern.


Final thoughts

Sliding window is one of those patterns that seems tricky until it “clicks.” Once you understand the idea of maintaining state as the window moves, you’ll be able to apply it to dozens of interview questions.

If you want a way to quickly see sliding window solutions explained step by step while practicing, you can check out StealthCoder. It overlays explanations in real time so you can focus on learning the reasoning rather than memorizing answers.