The same idea runs the other way as a difference array, which applies many range updates in O(1) each, and combines with a hash map to count subarrays with a given sum, even when values are negative and a sliding window can't be used.
When to use it
- You answer many range-sum (or count, or XOR) queries on an array that doesn't change.
- The question asks for the number of subarrays whose sum equals k or is divisible by k.
- Values can be negative, so shrinking a sliding window isn't safe.
- Many updates add a value to whole ranges, and you only need the final array.
- A grid problem asks for sums of rectangles.
The template
def subarray_sum_equals_k(nums, k):
seen = {0: 1} # prefix sum -> how many times it occurred
total = count = 0
for x in nums:
total += x # prefix sum up to and including x
count += seen.get(total - k, 0) # prefixes that leave exactly k
seen[total] = seen.get(total, 0) + 1
return count
# range sum [l, r) with prefix = [0, a0, a0+a1, ...]: prefix[r] - prefix[l]The variants you will meet
Building and querying
Start the prefix array with a 0 so prefix[i] is the sum of the first i items and every range [l, r) is prefix[r] - prefix[l]. The extra leading zero removes all the off-by-one special cases.
Counts, products, XOR and balance
Anything you can accumulate and undo works the same way: counts of values matching a test, XOR of a range, a +1/-1 balance for equal zeros and ones. Products need care, because a zero can't be divided out.
Prefix sums with a hash map
A subarray sums to k exactly when two prefix sums differ by k. Count earlier prefixes in a map as you go: Subarray Sum Equals K, subarrays divisible by k, and splitting an array into equal halves.
Difference arrays
To add v to every item in [l, r], add v at l and subtract it at r + 1; one prefix pass at the end rebuilds the array. Thousands of overlapping updates cost O(1) each.
2D prefix sums
In a grid, each cell stores the sum of the rectangle above and to its left. Any rectangle's sum is then four lookups combined by inclusion and exclusion, and difference arrays extend to 2D the same way.
Time and space complexity
Building the prefix array is O(n) time and O(n) space; each range query is then O(1). Subarray sum equals k is O(n) time and O(n) space for the map. A 2D table is O(m·n) to build with O(1) rectangle queries.