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^5See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI