DSA Master › Topic 4

Prefix Sum & Difference Arrays

prefix[i] is the sum of the first i elements, so the sum of any range [l, r] is prefix[r+1] − prefix[l] in O(1). Store prefix sums in a hash map to count subarrays with a target sum. A difference array does the reverse: it applies many range updates in O(1) each.

Concepts

How to recognise it

Common pitfalls

Problems

  1. Range Sum Query – Immutable (Easy)
  2. Find Pivot Index (Easy)
  3. Continuous Subarray Sum (Medium)
  4. Contiguous Array (Medium)
  5. Corporate Flight Bookings (Medium)
  6. Maximum Size Subarray Sum Equals K (Medium, Premium)