Skip to content
Craft

When to use prefix sum vs sliding window

Prefix sum vs sliding window is a choice about monotonicity and negative numbers, not about how the problem looks. Here is the test I use, with a worked example, operation counts, and a comparison table.

The prefix sum vs sliding window choice comes down to one question: does extending the range always push the answer in a single direction? If yes, because every element is nonnegative or the condition is monotone, use a sliding window. If values can be negative, or you must answer arbitrary range queries, use prefix sums.

How do you choose between a prefix sum and a sliding window?

You choose by testing whether the problem is monotone: if adding an element to the right end can only increase the measure, and removing one from the left can only decrease it, a sliding window is valid; otherwise you need prefix sums. Everything else is detail around that single test.

Both techniques apply to contiguous subarrays, which is why people confuse them. The word "subarray" in a problem statement triggers a reflex, and the reflex is usually the window, because the window is the technique most tutorials teach first. But the two tools answer different questions. A sliding window answers: what is the best range under this constraint, given that I can steer both ends by local decisions? A prefix sum answers: what is the aggregate of any range I care to name, after paying once up front?

Here is the framing I find useful, and it is not one you will see in most textbooks. Think of a prefix-sum array as the odometer readings you wrote down at every town on a road trip. You never recorded how far each leg was, only the running total. Yet the distance between any two towns is one subtraction, no matter how many towns lie between them. A sliding window is a different kind of traveller: a driver who can only see the last stretch of road through the rear window and has to decide, at each town, whether to drop the oldest stretch from consideration. The driver is fast and needs no notebook, but the driver's decision to drop the tail is only safe if dropping it could never make things better later. The notebook-keeper has no such assumption to defend.

That gives three tests, in the order I run them:

  1. Can the values be negative? If yes, a window that shrinks by dropping the left element has no guarantee about the direction the sum moves. Reach for prefix sums.
  2. Is it one question or many? A single pass that hunts for an optimal range suits a window. Many independent range queries suit prefix sums, because a window is tied to one traversal.
  3. Is the aggregate invertible? Prefix sums need subtraction to undo a prefix. Sum, count, XOR and modular sums qualify. Maximum and minimum do not, so range maximum needs a different structure.

Most interview problems are settled by the first test alone. I will show why with an example small enough to run by hand.

Why does a sliding window break when the array has negative numbers?

A sliding window breaks with negative numbers because its shrink rule relies on the sum falling when you drop the left element and rising when you add a right one. Negative values violate both assumptions, so the window can discard a prefix that a valid answer still needed.

Take the array [5, 6, -4] and ask for a contiguous subarray summing to exactly 7. The standard window logic goes like this: add elements on the right; whenever the sum exceeds the target, drop elements on the left until it no longer does.

  • Add 5. Sum is 5. Not 7, not over.
  • Add 6. Sum is 11, which exceeds 7. Drop 5. Sum is 6.
  • Add -4. Sum is 2. End of array. Nothing found.

The only valid answer is the whole array: 5 + 6 - 4 = 7. The window threw away the 5 at the moment the sum hit 11, reasoning that a smaller range was strictly closer to the target. That reasoning is only sound if everything still to come is nonnegative. Here the next element was -4, which pulled the sum back down and made the dropped 5 essential.

This is the entire failure mode, and it is worth stating as a rule: a sliding window is a greedy algorithm, and its greedy step is "the left element is never needed again once the window is too big." With nonnegative values that step is provably safe. Without them it is false, and no amount of cleverness in the loop condition repairs it. I have seen candidates patch the code with extra conditions for twenty minutes; the issue is not the code, it is that the invariant is gone. If you want the full treatment of the technique, the sliding window concept page covers the invariant in detail.

Contrast this with a case where the window is exactly right. Given positive numbers [2, 3, 1, 2, 4, 3] and a target of at least 7, find the shortest subarray whose sum reaches it. Grow right until the sum is at least 7: 2+3+1+2 = 8 (length 4). Now shrink: drop 2, sum is 6, below target, so grow: add 4, sum 10 (length 4, window [3,1,2,4]). Shrink: drop 3, sum 7 (length 3); drop 1, sum 6, grow: add 3, sum 9; shrink: drop 2, sum 7 (length 2, window [4,3]); drop 4, sum 3. End. The answer is 2. Every step touched each element at most twice, so it is O(n) time and O(1) space, and nothing could be done faster. Here the window wins outright, because every number is positive and shrinking always reduces the sum.

How does a prefix sum solve the negative-number case?

A prefix sum solves it by turning "does some subarray sum to k" into "do two prefix values differ by k", which is a lookup question that does not care whether the elements are positive or negative.

Define P[0] = 0 and P[i] as the sum of the first i elements. The sum of elements from index i to j-1 is P[j] - P[i]. So if you are standing at P[j] and want a subarray ending here with sum k, you need an earlier prefix equal to P[j] - k. Keep a hash map of how many times each prefix value has appeared, and the question becomes one dictionary lookup per element.

Here is a worked run on [3, 4, -7, 1, 3, 3, 1, -4] with k = 7. The prefix values are 0, 3, 7, 0, 1, 4, 7, 8, 4.

def count_subarrays(nums, k):
    seen = {0: 1}
    total = 0
    count = 0
    for x in nums:
        total += x
        count += seen.get(total - k, 0)
        seen[total] = seen.get(total, 0) + 1
    return count

Walking it by hand: after 3, total is 3 and we need -4, no match. After 4, total is 7 and we need 0, which has been seen once, so count becomes 1 (the subarray [3, 4]). After -7, total is 0, need -7, nothing; the map now holds 0 twice. After 1, total 1, nothing. After 3, total 4, nothing. After the second 3, total is 7, need 0, which has been seen twice, so count jumps to 3 (the subarrays [1, 3, 3] and the first six elements). After 1, total is 8, need 1, seen once, count becomes 4 (the subarray [3, 3, 1]). After -4, total 4, need -3, nothing. The answer is 4.

Notice the detail that trips people up: the map starts with {0: 1}. That entry represents the empty prefix, and without it you would miss every subarray that starts at index 0. Notice also the order of operations: look up before inserting, otherwise k = 0 would count an empty subarray against itself.

On the cost side, brute force on this 8-element array checks 36 subarrays. At n = 100,000 it is about 5 billion pairs (n(n+1)/2), which is several seconds in C++ and minutes in Python. The prefix-sum method does 100,000 map lookups and 100,000 map inserts, which finishes in tens of milliseconds even in Python. The speedup is not subtle: it is the difference between passing and a time limit exceeded verdict. This exact pattern is the heart of Subarray Sum Equals K, and the underlying mechanism is described in the prefix sums concept page.

What does each approach cost in time and memory?

A sliding window costs O(n) time and O(1) memory but only under a monotone condition, while prefix-sum methods cost O(n) preprocessing and O(n) memory but work without that condition and give O(1) per range query afterwards.

ApproachTimeExtra spaceNegatives allowedMany range queriesTypical use
Brute force over all pairsO(n^2)O(1)YesO(n) eachBaseline, small n
Sliding windowO(n)O(1)No (for sum conditions)NoShortest or longest range under a monotone constraint
Prefix sum arrayO(n) build, O(1) queryO(n)YesYesRepeated range sum queries
Prefix sum plus hash mapO(n) expectedO(n)YesNot applicableCount or detect subarrays with an exact sum
Monotonic deque on prefix sumsO(n)O(n)YesNot applicableShortest subarray with sum at least k, with negatives

The space column is the honest cost of prefix sums, and it is rarely the deciding factor. At n = 1,000,000 and 8-byte integers, the prefix array is 8 MB. I have seen the constant factor of a hash map matter far more than the array itself; if that is your bottleneck, why a hash map is slow is worth reading before you blame the algorithm.

When do range queries rule out a sliding window?

Range queries rule out a sliding window whenever the ranges are chosen by someone else, because a window is a single moving traversal and cannot jump to an arbitrary pair of endpoints.

Suppose an array has 200,000 elements and you receive 100,000 queries, each asking for the sum between positions l and r. A naive loop costs up to 200,000 additions per query, so the worst case is 2 x 10^10 operations, far beyond what any judge allows. Build the prefix array once (200,000 additions) and answer each query as P[r+1] - P[l]: 100,000 subtractions. Total work is around 300,000 operations, roughly 70,000 times less. The window offers nothing here, since no single pass can serve queries that arrive in arbitrary order.

The off-by-one is the usual bug. With P of length n + 1 and P[0] = 0, the inclusive sum of positions l through r is P[r+1] - P[l]. Many people instead make P the same length as the array and then special-case l = 0, which doubles the places an error can hide. I always use the extra leading zero and never regret it.

The invertibility test matters here too. Range sum, range XOR and range count of a value are invertible, so prefix arrays work. Range maximum is not: knowing the max of the first 50 elements and the max of the first 80 does not tell you the max of elements 51 to 80. For that you need a sparse table or a segment tree. This is why the same "contiguous range" phrase can send you to three very different structures, and why asking about the aggregate matters as much as asking about the range.

Can you combine prefix sums and sliding windows?

Yes, and the combination is often the intended solution when a problem has both negative numbers and an inequality target, because prefix sums remove the negatives problem while a monotonic structure restores the ability to discard candidates.

Consider finding the shortest subarray with a sum of at least k when negatives are allowed. A plain window fails for the reason we saw above. A plain prefix hash map fails too, because you need an inequality (P[j] - P[i] at least k), not an exact match, and a hash map cannot answer inequality questions. The workable approach keeps a deque of candidate prefix indices whose values are increasing. When a new prefix value arrives, you pop from the front while the difference from the front candidate reaches k (recording a length), and you pop from the back while the back candidate has a prefix value at least as large as the new one, since a later, smaller start is always better. Each index enters and leaves the deque once, so the whole thing is O(n).

What makes that work is that the monotonic discipline is restored on the prefix values even though the original values were not monotone. That is a good general lesson: when a greedy invariant fails on the raw data, check whether a transformed view of the data, such as prefix sums, brings the invariant back.

A smaller combination is common too. If you need the sum of every window of fixed size w, you can either maintain a running total (add the entering element, subtract the leaving one) or compute P[i+w] - P[i]. Both are O(n). The running total uses O(1) memory; the prefix version is easier to get right and lets you change w later without rewriting. For a one-off pass I use the running total; if I suspect the window size is a parameter I will have to vary, I use prefix sums. For the related question of how a window differs from two converging pointers, see the difference between sliding window and two pointers.

My position, stated plainly: if you are unsure, try the negative-number test first and default to prefix sums. A prefix-sum solution that was not strictly needed costs you some memory. A sliding-window solution applied where it is invalid costs you a wrong answer that passes the easy test cases and fails the hidden ones.

Frequently asked questions

Is a prefix sum always faster than a sliding window?

No. Both are O(n) for a single pass, but the sliding window needs only O(1) extra memory and avoids hash map overhead, so it is usually faster in practice when it applies. Prefix sums win on generality and on repeated queries, not on raw speed for one traversal.

Can I use a sliding window if the array has negative numbers?

Only if the condition you track is still monotone in some other way, for example the number of distinct characters in a window, which never decreases as you extend it. For sum-based conditions with negative values, the window's shrink step is unsafe, and you should switch to prefix sums with a hash map or a monotonic deque.

Why does the prefix-sum hash map start with the value 0 stored once?

That entry stands for the empty prefix before the first element. Without it, any subarray starting at index 0 would never find its matching earlier prefix, and you would undercount. For example, in [3, 4] with k = 7, the answer exists only because total 7 minus k equals the stored 0.

If you want to test the rule on a real problem, write the window solution for Subarray Sum Equals K first, find the input where it fails, and then replace it with the prefix-sum version.