Sliding Window Pattern – Part 1: The Core Pattern and Basic Problems

If you’re preparing for coding interviews or just want to sharpen your algorithm skills, the sliding window technique is one of the most important patterns to master. It shows up everywhere — from easy warm-ups to hard interview favorites — and once you see the pattern, you’ll recognize it instantly.

In this 3-part series, I’ll walk you through 8 LeetCode problems that all use sliding window, progressing from the simplest form to more advanced variations. By the end, you’ll have a clear mental model for when and how to apply this technique.


What Is the Sliding Window Pattern?

Imagine you have an array and you need to look at every contiguous subarray of size k. The brute-force approach recalculates everything from scratch for each subarray — that’s O(nk). But notice: when the window slides one position to the right, only one element enters and one element leaves. Everything in the middle stays the same.

The sliding window technique exploits this overlap. Instead of recomputing, you update the result by adding the new element and removing the old one. This brings the time complexity down to O(n).

The general template looks like this:

  1. Initialize the window with the k elements
  2. Slide the window one step at a time: add nums[i], remove nums[i-k]
  3. Update your answer at each step

Let’s see this in action with three problems.


Problem 1: Moving Average from Data Stream (LC 346)

Difficulty: Easy

Problem: Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Key Insight: This is the purest form of sliding window. You maintain a queue of the last size numbers. Each time a new number arrives, push it in. If the queue exceeds the window size, pop the oldest number. Track the running sum so you can return the average in O(1).

Solution (C++)

cpp

class MovingAverage {
    int sum;
    queue<int> numbers;
    int size;
public:
    MovingAverage(int size) : sum(0), size(size) {

    }

    double next(int val) {
        sum += val;
        numbers.push(val);
        if (numbers.size() > size) {
            sum -= numbers.front();
            numbers.pop();
        }
        return (double)sum / numbers.size();
    }
};

Why It Works

  • sum tracks the running total so we never re-sum the entire window.
  • The queue naturally maintains insertion order — front() is always the oldest element.
  • When the queue grows beyond size, we subtract the front element from sum and pop it.

Time: O(1) per next() call
Space: O(k) where k = window size


Problem 2: Maximum Average Subarray I (LC 643)

Difficulty: Easy

Problem: Given an integer array nums and an integer k, find the contiguous subarray of length k with the maximum average value.

Key Insight: Same sliding window, but now instead of a stream, you have a fixed array. Compute the sum of the first k elements, then slide: add the new element, subtract the one that fell off. Track the maximum sum seen so far, and divide by k at the end.

Brute Force vs. Sliding Window

  • Brute force: For each starting index, sum up k elements → O(nk)
  • Sliding window: Maintain a running sum, update in O(1) per step → O(n)

Solution (C++)

cpp

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        int sumSoFar = 0;
        for (int i = 0; i < k; ++i) {
            sumSoFar += nums[i];
        }
        int maxSum = sumSoFar;
        for (int i = k; i < nums.size(); ++i) {
            sumSoFar += nums[i];
            sumSoFar -= nums[i-k];
            maxSum = max(maxSum, sumSoFar);
        }

        return (double)maxSum / k;
    }
};

Walkthrough

For nums = [1, 12, -5, -6, 50, 3] and k = 4

WindowElementsSum
[0..3]1, 12, -5, -62
[1..4]12, -5, -6, 5051
[2..5]-5, -6, 50, 342

Maximum sum is 51 → average = 51 / 4 = 12.75

Notice the two-phase structure: first loop initializes the window sum, second loop slides it. This is the canonical fixed-size sliding window template.

Time: O(n)
Space: O(1)


Problem 3: Number of Sub-arrays of Size K with Average ≥ Threshold (LC 1343)

Difficulty: Medium

Problem: Given an array arr, integers k and threshold, return the number of sub-arrays of size k whose average is greater than or equal to threshold.

Key Insight: Identical sliding window — the only change is what you do at each window position. Instead of tracking the max sum, you count how many windows meet the condition sum / k >= threshold.

Solution (C++)

cpp

class Solution {
public:
    int numOfSubarrays(vector<int>& arr, int k, int threshold) {
        int sum = accumulate(begin(arr), begin(arr) + k, 0);
        int result = sum / k >= threshold ? 1 : 0;

        for (int i = k ; i < arr.size(); ++i) {
            sum -= arr[i-k];
            sum += arr[i];
            result += sum / k >= threshold ? 1 : 0;
        }

        return result;
    }
};

What Changed?

Compared to the previous problem, only line that evaluates the window changed. Instead of maxSum = max(…), we have result += (condition) ? 1 : 0. The window mechanics are identical.

This is the beauty of the sliding window pattern: the window management code is the same every time. Only the evaluation logic changes based on what the problem asks.

Time: O(n)
Space: O(1)


The Pattern So Far

All three problems share this structure:

1. Compute initial window (first k elements)
2. Evaluate initial window
3. For i = k to n-1:
     a. Add nums[i] to window state
     b. Remove nums[i-k] from window state
     c. Evaluate current window
4. Return result

The only thing that varies is:

  • What state you track (sum, count, etc.)
  • How you evaluate (return average, track max, count matches)

In Part 2, we’ll see how this same pattern handles more interesting conditions — counting vowels, dealing with grumpy bookstore owners, and checking for unique characters.

Leave a Reply

Your email address will not be published. Required fields are marked *