Count of Range Sum
1 approach, code in every language
Problem description
Given an integer array along with an inclusive lower and upper bound, count how many contiguous slices have a sum that lands inside the bound. Equivalently, count index pairs i ≤ j whose slice total falls between lower and upper, both inclusive.
Building a prefix-sum array turns each slice total into the difference of two prefix sums. Counting pairs of prefix sums whose difference stays inside the bound can then be folded into a merge sort, which counts qualifying pairs while it merges sorted halves.
Example 1
Input: nums = [-2,5,-1], lower = -2, upper = 2
Output: 3
The slices that total within [-2, 2] are [-2] (sum -2), [-1] (sum -1), and [-2,5,-1] (sum 2).
Example 2
Input: nums = [0], lower = 0, upper = 0
Output: 1
The single slice [0] sums to 0, which lies in the range.
Constraints
1 ≤ nums.length ≤ 10^5-2^31 ≤ nums[i] ≤ 2^31 - 1-10^5 ≤ lower ≤ upper ≤ 10^5
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reservoir Swing Bands is our own problem on the technique behind Count of Range Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free