Skip to lesson

Many contiguous subarray problems ask about every group of exactly k consecutive items: the largest k-day revenue sum, the average of every k-reading sensor window, or how many k-element windows meet a threshold. A fixed-size sliding window solves all three with the same two-phase loop in O(n) time and O(1) extra space.

Maximum sum of k elements

A fixed-size window always covers exactly k consecutive elements; each step adds the new element and removes the one that left.

Given an integer array nums and an integer k (1 ≤ k ≤ n), suppose we want the maximum sum of any contiguous subarray of length k.

  1. Validate that k > 0 and k <= nums.length.
  2. Sum the first k elements (indices 0 .. k - 1) into a long windowSum and initialize maxSum = windowSum.
  3. Loop right from k to nums.length - 1: windowSum += nums[right] - nums[right - k].
  4. Update maxSum = Math.max(maxSum, windowSum) after each slide.

Example 1 · Brute force: sum every window again (O(n · k) time, O(1) space)

MaxSumFixedBrute.javaJava
public class MaxSumFixedBrute {    public static long maxSubarraySumOfSizeK(int[] nums, int k) {        long best = Long.MIN_VALUE;        for (int start = 0; start + k <= nums.length; start++) {            long sum = 0;            for (int i = start; i < start + k; i++) {                sum += nums[i];            }            best = Math.max(best, sum);        }        return best;    }
    public static void main(String[] args) {        int[] mixed = {4, -1, 2, 1, -5, 4};        System.out.println("Max sum (k=3) in mixed: " + maxSubarraySumOfSizeK(mixed, 3));
        int[] allNeg = {-8, -3, -5, -2, -9};        System.out.println("Max sum (k=2) in allNeg: " + maxSubarraySumOfSizeK(allNeg, 2));    }}
Output
Max sum (k=3) in mixed: 5
Max sum (k=2) in allNeg: -7

What this code does

  • Each start index adds k numbers, so n windows cost about n × k additions.
  • Starting best at Long.MIN_VALUE keeps all-negative arrays correct. The slowdown comes from adding the same k - 1 numbers again for the next window.

Example 2 · Optimal: slide the window, one add and one subtract (O(n) time, O(1) space)

MaxSumFixedWindowDemo.javaJava
public class MaxSumFixedWindowDemo {    public static long maxSubarraySumOfSizeK(int[] nums, int k) {        if (nums == null || k <= 0 || k > nums.length) {            throw new IllegalArgumentException("Invalid window size k");        }        long windowSum = 0;        for (int i = 0; i < k; i++) {            windowSum += nums[i];        }        long maxSum = windowSum;        for (int right = k; right < nums.length; right++) {            windowSum += nums[right] - nums[right - k];            if (windowSum > maxSum) {                maxSum = windowSum;            }        }        return maxSum;    }
    public static void main(String[] args) {        int[] mixed = {4, -1, 2, 1, -5, 4};        System.out.println("Max sum (k=3) in mixed: " + maxSubarraySumOfSizeK(mixed, 3));
        int[] allNeg = {-8, -3, -5, -2, -9};        System.out.println("Max sum (k=2) in allNeg: " + maxSubarraySumOfSizeK(allNeg, 2));    }}
Output
Max sum (k=3) in mixed: 5
Max sum (k=2) in allNeg: -7

What this code does

  • In mixed with k=3, the windows are [4,-1,2]=5, [-1,2,1]=2, [2,1,-5]=-2, and [1,-5,4]=0; the maximum is 5.
  • In allNeg with k=2, initializing maxSum to the first window (-11) allows the slide to [-5,-2]=-7 to properly win.
  • Why it is faster: the next window differs by one number in and one number out, so each slide costs O(1) instead of O(k).

A brute-force nested loop checks all n - k + 1 starting indices and sums k elements each time in O(n · k) time.

Instead, we can build the first window of length k by summing indices 0 through k - 1 and setting maxSum = windowSum. Then, for each incoming right index right from k to n - 1, we add nums[right] and subtract the outgoing element nums[right - k]. Each slide updates windowSum in O(1) time, and we update maxSum = Math.max(maxSum, windowSum).

Find the bug

Find the window bug

Tap the line that is wrong.

This code gives 0 for an array of only negative numbers. Which line is wrong?

Round 1 of 2
Always initialize maxSum to the first window's sum (or Long.MIN_VALUE before the first window completes), never to 0, because an array of all negative numbers has a negative maximum sum.

Average of every window

Sometimes a problem asks for the average of every k-element subarray (or the maximum average of length k). Because dividing by k is a monotonic scaling operation for positive k, the window with the maximum sum also has the maximum average.

Example 3 · Rolling averages of every window of size k

RollingAveragesDemo.javaJava
import java.util.Arrays;
public class RollingAveragesDemo {    public static double[] movingAverages(int[] nums, int k) {        int n = nums.length;        double[] result = new double[n - k + 1];        long windowSum = 0;
        for (int right = 0; right < n; right++) {            windowSum += nums[right];            if (right >= k) {                windowSum -= nums[right - k];            }            if (right >= k - 1) {                result[right - k + 1] = (double) windowSum / k;            }        }        return result;    }
    public static void main(String[] args) {        int[] readings = {2, 4, 6, 8, 10, 12};        double[] avgs = movingAverages(readings, 3);        System.out.println(Arrays.toString(avgs));    }}
Output
[4.0, 6.0, 8.0, 10.0]

What this code does

  • A single loop grows the window until right == k - 1 (index 2), where the first full window [2, 4, 6] has average 4.0.
  • For right >= k, nums[right - k] is subtracted before recording the average at index right - k + 1.
  • Number of windows of size k in an array of length n: n - k + 1.
  • Outgoing index when right enters the window: right - k.
  • Output index for the window ending at right: right - k + 1.
  • Prefer exact integer/long addition and subtraction for the running sum, then divide by (double) k when recording the average.

If you need an array of all n - k + 1 window averages, there are n - k + 1 windows in an array of length n. Maintain the running sum as a long (or double) and store (double) windowSum / k at output index right - k + 1. Keeping windowSum as an exact long avoids accumulating floating-point rounding drift across millions of slides.

Counting windows that meet a rule

Many problems ask you to count the windows of length k that meet a rule.

Example 4 · Counting k-length windows that meet an average or vowel rule

CountValidWindowsDemo.javaJava
public class CountValidWindowsDemo {    public static int numOfSubarraysAtLeastThreshold(int[] arr, int k, int threshold) {        long targetSum = (long) k * threshold;        long windowSum = 0;        int count = 0;
        for (int right = 0; right < arr.length; right++) {            windowSum += arr[right];            if (right >= k) {                windowSum -= arr[right - k];            }            if (right >= k - 1 && windowSum >= targetSum) {                count++;            }        }        return count;    }
    private static boolean isVowel(char c) {        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';    }
    public static int maxVowelsInSubstring(String s, int k) {        int vowels = 0;        int maxVowels = 0;        for (int right = 0; right < s.length(); right++) {            if (isVowel(s.charAt(right))) {                vowels++;            }            if (right >= k && isVowel(s.charAt(right - k))) {                vowels--;            }            if (right >= k - 1 && vowels > maxVowels) {                maxVowels = vowels;            }        }        return maxVowels;    }
    public static void main(String[] args) {        int[] arr = {2, 2, 2, 2, 5, 5, 5, 8};        System.out.println("Windows with avg >= 4: " + numOfSubarraysAtLeastThreshold(arr, 3, 4));        System.out.println("Max vowels (k=3) in abciiidef: " + maxVowelsInSubstring("abciiidef", 3));    }}
Output
Windows with avg >= 4: 3
Max vowels (k=3) in abciiidef: 3

What this code does

  • Converting average >= threshold into windowSum >= (long) k * threshold keeps the check exact and fast.
  • In maxVowelsInSubstring, the state is the vowel count in the current k-char window, updated in O(1) as characters enter and leave.

A common variation asks: "How many contiguous subarrays of length k have an average at least threshold (or contain at most x defects)?" Notice that windowSum / (double) k >= threshold is mathematically equivalent to windowSum >= (long) threshold * k when threshold is an integer, which avoids floating-point division inside the loop.

More generally, a fixed-size window can maintain any incremental state—such as a count of odd numbers, a count of vowels in a k-character substring, or a frequency array—as long as you can apply the effect of in = arr[right] and undo the effect of out = arr[right - k] in O(1) time.

  • For sum/average thresholds: check windowSum >= (long) threshold * k on the first window and after every slide.
  • For property counts (such as vowels in a length-k substring): increment count if s.charAt(right) matches, decrement if s.charAt(right - k) matches.
  • Single-loop style: add right, if right >= k remove right - k, and if right >= k - 1 evaluate the window.

Next step

Check your understanding

10 quick questions