Fixed-size Window

A fixed-size window keeps the window length constant (e.g. k) while sliding it over the array or string. You maintain a running value (sum, count, etc.) and update it when the window moves by one position.

When to Use

  • The problem asks for something about every contiguous block of size k (max sum, average, pattern count).
  • You can update the metric in O(1) when the window slides (add one new element, remove one old element).

Template

Java
// Compute something for each window of size k
int left = 0;
for (int right = 0; right < n; right++) {
    // Add nums[right] to window
    if (right - left + 1 == k) {
        // Update answer for window [left, right]
        // Remove nums[left] from window
        left++;
    }
}

Maximum Sum Subarray of Size K

Find the maximum sum among all contiguous subarrays of length k.

  • Maintain windowSum; when the window reaches size k, update maxSum and subtract nums[left] before moving left.
Java
public int maxSumSubarray(int[] nums, int k) {
    int n = nums.length;
    int windowSum = 0, maxSum = 0;
    for (int i = 0; i < k; i++) windowSum += nums[i];
    maxSum = windowSum;
    for (int right = k; right < n; right++) {
        windowSum += nums[right] - nums[right - k];
        maxSum = Math.max(maxSum, windowSum);
    }
    return maxSum;
}

Summary

For fixed-size windows, keep the window at length k, update the metric in O(1) when sliding, and record the best (or aggregate) over all windows.