Software Engineer (SDE)dsabeginner3 interactive MCQs in app
Prefix Sum & Difference Arrays
O(1) range query after O(n) build1-indexed pref[0] = 0 conventionprefix-sum + hashmap for negative-number subarrays
Core Concept
A prefix sum array `pref` precomputes cumulative sums (`pref[0] = 0`, `pref[i+1] = pref[i] + nums[i]`) in O(n) setup time so ANY subarray sum `[L..R]` (inclusive) is answered in O(1) via `pref[R + 1] - pref[L]`. Leading `pref[0] = 0` eliminates special `if L == 0` branches! Combined with a hash map of seen prefix sums, you can even count subarrays summing to `k` in O(n) when negatives exist (where sliding window fails).
Worked Example
`nums = [2, 4, 1]` -> `pref = [0, 2, 6, 7]`; sum `[1..2]` = `pref[3] - pref[1] = 7 - 2 = 5`.
Common Pitfall
off-by-one errors between `pref[R] - pref[L-1]` vs `pref[R+1] - pref[L]`.
Recommended Readings & Practice
Practice Prefix Sum & Difference Arrays with 3 graded MCQs & written feedback.
Take SOARDO’s free 12-question diagnostic to see how strong you are across your target role and unlock adaptive daily missions.