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
- Prefix sums
- Prefix frequency maps
- Difference arrays
- Range queries
How to recognise it
- You need many range-sum queries on an array that doesn't change.
- The problem says "count subarrays with sum k", and the values can be negative.
- You need to apply lots of "add v to the range [l, r]" updates, then read the result once.
Common pitfalls
- Don't forget the base entry: count.put(0, 1) for counting, or first.put(0, -1) when you need lengths.
- For "divisible by k" problems, normalise negative remainders: ((sum % k) + k) % k.
Problems
- Range Sum Query – Immutable (Easy)
- Find Pivot Index (Easy)
- Continuous Subarray Sum (Medium)
- Contiguous Array (Medium)
- Corporate Flight Bookings (Medium)
- Maximum Size Subarray Sum Equals K (Medium, Premium)