Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.

Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-2,5,-1], lower = -2, upper = 2
Output: 3
💡 Note: Three range sums in [-2,2]: subarray [-2] sum=-2, subarray [-1] sum=-1, subarray [5,-1] sum=4. Wait, 4 is not in [-2,2]. Let me recalculate: [-2] sum=-2 ✓, [5] sum=5 ✗, [-1] sum=-1 ✓, [-2,5] sum=3 ✗, [5,-1] sum=4 ✗, [-2,5,-1] sum=2 ✓. So we have 3 valid sums.
Example 2 — Single Element
$ Input: nums = [0], lower = 0, upper = 0
Output: 1
💡 Note: Only one possible range sum: [0] which equals 0, and 0 is in range [0,0]
Example 3 — No Valid Ranges
$ Input: nums = [-3,-1], lower = 1, upper = 2
Output: 0
💡 Note: All possible sums are negative: [-3]=-3, [-1]=-1, [-3,-1]=-4. None are in range [1,2]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -231 ≤ nums[i] ≤ 231 - 1
  • -105 ≤ lower ≤ upper ≤ 105

Visualization

Tap to expand
Count of Range Sum INPUT nums array: -2 i=0 5 i=1 -1 i=2 Range bounds: lower = -2, upper = 2 Prefix Sums: 0 -2 3 2 All range sums S(i,j): S(0,0)=-2, S(0,1)=3, S(0,2)=2 S(1,1)=5, S(1,2)=4, S(2,2)=-1 ALGORITHM STEPS 1 Compute Prefix Sums prefix[i] = sum(nums[0..i-1]) 2 Merge Sort Approach Divide array, count in halves 3 Count Cross Ranges For each i, find j where lower <= p[j]-p[i] <= upper 4 Merge and Sum Total = left + right + cross Valid Range Sums (in [-2, 2]): S(0,0)=-2 S(0,2)=2 S(2,2)=-1 Others (3, 5, 4) are out of range FINAL RESULT Count of valid range sums: 3 Breakdown: 1. S(0,0) = -2 OK 2. S(0,2) = 2 OK 3. S(2,2) = -1 OK All in range [-2, 2] Time: O(n log n) Space: O(n) Key Insight: Range sum S(i,j) = prefix[j+1] - prefix[i]. The problem transforms to counting pairs (i,j) where lower <= prefix[j] - prefix[i] <= upper. Using merge sort, we can count these pairs in O(n log n) by leveraging the sorted property during the merge phase to find valid ranges efficiently. TutorialsPoint - Count of Range Sum | Optimal Solution (Merge Sort)
Asked in
Google 35 Microsoft 28 Amazon 22
78.0K Views
Medium Frequency
~35 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen