Prefix sums
Turn range calculations into subtraction.
A prefix belongs to a boundary between elements; subtracting two boundaries describes one interval.
Mechanism and state
Define P[b] as the sum of the first b values, including P[0]=0. Half-open range [left,right) has sum P[right]-P[left]. Build a private snapshot for immutable queries. In counting scans, the map payload depends on the objective: frequencies count all earlier matches, while earliest boundaries maximize length. Equal binary counts become repeated ones-minus-zeroes balances; divisible sums become repeated normalized remainder classes. A 2D summed-area table extends cancellation with inclusion-exclusion.
Why the pattern works
Explain the boundary meaning before the algebra. Subtracting equal prefixes isolates a zero sum; equal normalized residues isolate a sum divisible by k. For counting, query earlier-state frequencies before inserting the current boundary and seed the empty prefix once. For longest ranges, keep the earliest occurrence instead of overwriting it. In 2D, the overlap removed by both strips must be added back. Immutable queries must depend on stored snapshot values, not mutable caller arrays.
Work through an example
For [2,-1,3], P=[0,2,1,4]; [1,3) sums to P[3]-P[1]=2, and [2,2) is zero. For binary [0,1,0,1], balances at boundaries are [0,-1,0,-1,0]; preserving the first zero boundary gives length four. For [-1,5] with modulus five, prefixes -1 and 4 both normalize to residue four and identify the divisible range [5].
Where the reasoning fails
Do not mix element indices with prefix boundaries or inclusive ends with half-open ends. A set cannot replace frequencies when repeated states represent multiple starts; a latest-position map cannot replace earliest boundaries for longest length. Java remainder may be negative, so normalize modulo classes. Wide sums and quadratic counts need long. Product windows cannot use sum subtraction; DSA-032 instead requires positive factors, exact division, and an overflow guard before multiplication.
Reconstruct the reasoning
Trace half-open queries and an empty range on [2,-1,3]. Compare frequency versus earliest-boundary maps on [0,1,0,1]. Normalize every prefix residue of [-1,5] modulo five. Derive the four inclusion-exclusion signs for one interior matrix cell and explain why later source mutations must not affect a snapshot query.
Apply this foundation
- Two Sum · Explanation
- Product of Array Except Self · Explanation
- Range Sum Query — Immutable · Explanation
- Subarray Sum Equals K · Explanation
- Contiguous Array — Equal Zeroes and Ones · Explanation
- Subarray Product Less Than K · Explanation
- Count Subarrays Divisible by K · Explanation
- Range Sum Query 2D — Immutable · Explanation