Browse Curriculum
Sliding Window
Medium

Overview (Fixed Length)

Master the fixed-size sliding window pattern: slide one element out, slide one element in.

What is a Fixed Length Window?

In a Fixed Length sliding window, the size of the window k never changes. Visualizing it is simple: imagine a rigid frame of size k sliding across your array one step at a time.

The Golden Rule:
At each step, we do exactly two things in O(1) time:

  1. Remove the element leaving the window (the one at i - k).
  2. Add the element entering the window (the one at i).

This "Add-Remove" strategy avoids re-calculating the window content from scratch, turning an O(N*K) brute force algorithm into an O(N) linear solution.

Core Problem: Maximum Sum Subarray of Size K

The classic problem to learn this pattern:

Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.

Example:

  • Input: nums = [2, 1, 5, 1, 3, 2], k = 3
  • Output: 9
  • Explanation: Subarray [5, 1, 3] has the largest sum.

Algorithm Strategy

  1. Initialize: Calculate the sum of the first k elements. Set this as your initial current_sum and max_sum.
  2. Slide: Iterate from index k to the end of the array.
  3. Update: For each new element at index i:
    • Add nums[i] to current_sum.
    • Subtract nums[i - k] (the element falling out) from current_sum.
    • Update max_sum = max(max_sum, current_sum).
  4. Return: max_sum.

Visual Walkthrough

Step 1 / 1

Initializing...

1x

Watch how the window slides. Notice that we don't re-add the middle elements; we purely adjust for the entering and leaving numbers.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.