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 with difference arrays.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Array and String Fundamentals, Hash Tables and Hashing Patterns

A prefix sum array stores pre[i] = a[0] + ... + a[i-1]. Then the sum of any range [l, r] is pre[r + 1] - pre[l] in O(1) after O(n) preprocessing. Using a leading zero (size n + 1) removes most boundary special cases.

Patterns

  • Range sum queries on a static array.
  • Subarray sum equals k: as you scan, keep a hash map of how many times each prefix sum has occurred. At index i, the number of subarrays ending here with sum k equals count[pre - k]. Initialise count[0] = 1. This works with negative numbers, unlike sliding window.
  • Divisibility: subarrays with sum divisible by k use prefix sums modulo k.
  • Balance tricks: map 0 to -1 and find the longest subarray with equal 0s and 1s (longest prefix-sum repeat).
  • 2D prefix sums for sub-rectangle sums using inclusion-exclusion.

Difference arrays

To add v to every element in [l, r] many times, do d[l] += v; d[r + 1] -= v, then take a prefix sum at the end. This is the offline version of range updates and powers problems like Car Pooling and Corporate Flight Bookings.

Other prefix variants: prefix XOR, prefix max/min, and prefix products (Product of Array Except Self uses prefix and suffix products).

Pitfall: prefix sums can overflow int; use 64-bit.

Key concepts

  • 1D prefix sums with leading zero
  • Prefix sum + hash map counting: Subarray Sum Equals K
  • Prefix sums modulo k
  • 2D prefix sums
  • Difference arrays for range updates
  • Prefix XOR and products

Mini project

Solve 8 problems: Range Sum Query Immutable, Subarray Sum Equals K, Continuous Subarray Sum, Contiguous Array, Subarray Sums Divisible by K, Range Sum Query 2D, Car Pooling, and Corporate Flight Bookings.

Check yourself

In Subarray Sum Equals K, why must the hash map start with count[0] = 1?

Free resources