What are Sliding Window and Prefix Sum?
Solution and explanation
Sliding window
A window is a contiguous range [left, right] of an array or string. Instead of recomputing every subarray from scratch, slide the window: add the element entering on the right and remove the one leaving on the left. This turns many O(n·k) or O(n²) problems into O(n).
- Fixed-size window: size k stays constant (maximum sum of k consecutive days of sales).
- Variable-size window: expand right until a condition breaks, then shrink left until it holds again (longest substring without repeats, smallest subarray with sum ≥ target).
// Fixed window template
int windowSum = 0;
for (int right = 0; right < a.length; right++) {
windowSum += a[right]; // element enters
if (right >= k) windowSum -= a[right - k]; // element leaves
if (right >= k - 1) { /* use windowSum */ }
}
Prefix sum
prefix[i] = a[0] + … + a[i−1]. Then the sum of any range [l, r] is prefix[r+1] − prefix[l] in O(1) after O(n) preprocessing.
a = [3, 1, 4, 1, 5]
prefix = [0, 3, 4, 8, 9, 14]
sum(1..3) = prefix[4] - prefix[1] = 9 - 3 = 6 (1 + 4 + 1)
int[] prefix = new int[a.length + 1];
for (int i = 0; i < a.length; i++) prefix[i + 1] = prefix[i] + a[i];
int rangeSum = prefix[r + 1] - prefix[l];
Prefix sum + HashMap
Storing counts of prefix sums in a HashMap answers "how many subarrays sum to k" in O(n), even with negative numbers (where a sliding window fails).
When to use which
- All numbers non-negative and you need contiguous ranges → sliding window.
- Many range-sum queries or negative numbers → prefix sums (with a HashMap).
Complexity
- Sliding window: O(n) time, O(1) or O(k) space. Prefix sums: O(n) build, O(1) per query, O(n) space.
