Prefix Sum
Store the running total of an array once, then answer any range sum by one subtraction, and count subarrays with a given sum by looking up earlier totals in a hash map.
Overview
The idea
A prefix sum is the total of the first i elements of an array. Write the totals down once, in an array prefix with prefix[0] = 0 and prefix[i] = prefix[i - 1] + nums[i - 1]. Then the sum of any range nums[l..r] is one subtraction: prefix[r + 1] - prefix[l]. The elements before l are counted in both totals, so they cancel.
The extra zero at the front matters. It means a range that starts at index 0 is handled by the same formula as any other range, with nothing special to check.
Build the array for [2, 4, 1, 5, 3, 7]. prefix[0] is 0, the sum of no elements. Each later entry adds the next element: prefix[1] is 2, prefix[2] is 2 + 4 = 6, prefix[3] is 2 + 4 + 1 = 7, prefix[4] is 2 + 4 + 1 + 5 = 12, prefix[5] is 2 + 4 + 1 + 5 + 3 = 15, and prefix[6] is 22, the whole array. So prefix is [0, 2, 6, 7, 12, 15, 22].
Now every range query on that array is a single subtraction.
- nums[2..4]: prefix[5] - prefix[2] = 15 - 6 = 9, which checks out as 1 + 5 + 3.
- nums[0..5]: prefix[6] - prefix[0] = 22 - 0 = 22, the whole array.
- nums[3..3]: prefix[4] - prefix[3] = 12 - 7 = 5, a single element.
The lab below builds this array and answers the first query; change l and r to try the others. Its other tabs, Count sum k, Divisible by k and Equal 0s, 1s, trace the examples later in this chapter.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio