📏

Fixed Sliding Window

Window of exactly k elements slides one position at a time. Build once in O(k), then add right element − remove left element in O(1) per step.

Array String Time O(n) Space O(1)
📋 When to Use
  • Window size k is fixed and given in the problem
  • Find max / min / average of every window of size k
  • Count elements matching a condition in each window
  • Subarray / substring of length exactly k
💡 Naive O(n·k) recomputes each window. Sliding window maintains a running total for O(n) — k× faster.
⚡ Complexity
Time
O(n)
Space
O(1)

Each element is touched exactly twice — once entering, once leaving. Single pass, constant extra memory (just a few integers).

Live Animation · Fixed Sliding Window · LC #643
Problem Given an integer array nums and an integer k, find the maximum average value of any contiguous subarray of length k. Here we show maximum sum for clarity — divide by k to get the average.
Input: nums = [2, 1, 5, 1, 3, 2], k = 3  ·  Answer: window [5,1,3] → sum = 9, avg = 3.0
Step 1 / —
🔨 Phase 1: Build (i = 0 → k−1)
🪟 Phase 2: Slide (i = k → n−1)
✅ Done
nums = [2, 1, 5, 1, 3, 2]    k = 3
windowSum =
maxSum =
window =
Click ▶ Play or Next ▶ to start
Initialize: int windowSum = 0, maxSum = 0;
Complete Java TemplateJAVA
int maxWindowSum(int[] nums, int k) {
    int windowSum = 0;

    // ── Phase 1: Build first window ──────────────────────
    for (int i = 0; i < k; i++) {
        windowSum += nums[i];
    }
    int maxSum = windowSum;

    // ── Phase 2: Slide window one step at a time ─────────
    for (int i = k; i < nums.length; i++) {
        windowSum += nums[i] - nums[i - k];   // add right, remove left
        maxSum = Math.max(maxSum, windowSum);
    }

    return maxSum;   // O(n) time, O(1) space
}
🎯 Practice Problems