Prefix Sums and Difference Arrays

Precompute running totals to answer range-sum queries in O(1), count subarrays with a target sum, and apply range updates cheaply.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Sliding Window

A prefix sum array stores the total of the first i elements, so any range sum is one subtraction. Combine it with a hash map and it solves a whole family of subarray counting problems.

Key patterns

  • Range sum query: sum(l..r) = pre[r + 1] - pre[l]. Range Sum Query - Immutable.
  • 2D prefix sums: rectangle sums with inclusion-exclusion (Range Sum Query 2D).
  • Prefix sum + hash map: count subarrays with sum k by storing how often each prefix value has appeared (Subarray Sum Equals K). Works with negative numbers, unlike sliding window.
  • Prefix modulo: Subarray Sums Divisible by K, Continuous Subarray Sum.
  • Prefix of a transformed array: treat 0 as -1 to find the longest subarray with equal 0s and 1s (Contiguous Array).
  • Difference array: add v to a range in O(1) by updating two cells, then prefix-sum once (Corporate Flight Bookings, Car Pooling).
  • Prefix and suffix products: Product of Array Except Self without division.

Pitfalls

  • Off-by-one between 0-indexed arrays and 1-indexed prefix arrays. Pick one convention and stick to it.
  • Forgetting to seed the map with prefix 0 seen once.
  • Negative remainders in languages where -3 % 5 is -3; normalise with ((x % k) + k) % k.

You are ready to move on when you can solve Subarray Sum Equals K and explain why the map must start with {0: 1}.

Key concepts

  • 1D prefix sums
  • 2D prefix sums
  • Prefix sum with hash map
  • Prefix modulo
  • Difference arrays
  • Prefix and suffix products

Mini project

Solve these 10 in 7 days, log time and pattern: Running Sum of 1d Array, Range Sum Query - Immutable, Find Pivot Index, Product of Array Except Self, Subarray Sum Equals K, Contiguous Array, Subarray Sums Divisible by K, Range Sum Query 2D - Immutable, Corporate Flight Bookings, Car Pooling.

Check yourself

How does a difference array let you apply 1e5 range updates and then read the final array in O(n + q)?

Free resources