Count of Range Sum - Problem
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
Understanding the Visualization
1
Input
Array nums=[-2,5,-1], range=[-2,2]
2
Process
Find all subarrays with sum in [-2,2]
3
Output
Count = 3 valid range sums
Key Takeaway
🎯 Key Insight: Transform to prefix sum differences and use divide & conquer for optimal O(n log n) counting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code