Count of Range Sum - Problem
Count of Range Sum is a challenging problem that asks you to find how many subarray sums fall within a given range.
You're given an integer array
A range sum
Goal: Return the total count of range sums that satisfy
You're given an integer array
nums and two integers lower and upper. Your task is to count how many range sums lie in the interval [lower, upper] inclusive.A range sum
S(i, j) is defined as the sum of elements from index i to index j (where i ≤ j). For example, in array [1, 2, 3], the range sums are: 1, 2, 3, 1+2=3, 2+3=5, and 1+2+3=6.Goal: Return the total count of range sums that satisfy
lower ≤ range_sum ≤ upper. Input & Output
example_1.py — Basic Case
$
Input:
nums = [-2, 5, -1], lower = -2, upper = 2
›
Output:
3
💡 Note:
The valid range sums are: [-2] = -2, [-1] = -1, and [-2, 5, -1] = 2. All three fall within the range [-2, 2].
example_2.py — All Positive
$
Input:
nums = [1, 2, 3], lower = 3, upper = 5
›
Output:
2
💡 Note:
Valid range sums are: [3] = 3 and [1, 2] = 3. Both equal 3 which is in range [3, 5]. [2, 3] = 5 is also valid.
example_3.py — Single Element
$
Input:
nums = [0], lower = 0, upper = 0
›
Output:
1
💡 Note:
Only one range sum possible: [0] = 0, which exactly matches the range [0, 0].
Visualization
Tap to expand
Understanding the Visualization
1
Convert to prefix sums
Transform the problem into cumulative sums
2
Use divide and conquer
Split array and count cross-boundary valid ranges
3
Merge and count
Combine results while maintaining sorted order
Key Takeaway
🎯 Key Insight: Convert range sum counting to prefix sum differences, then use efficient sorting-based algorithms to count valid pairs in O(n log n) time.
Time & Space Complexity
Time Complexity
O(n² log n)
For each of n positions, we do binary search (log n) and insertion (O(n)) in sorted list
⚠ Quadratic Growth
Space Complexity
O(n)
Space for prefix sums and sorted list of previous prefix sums
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 105
- -231 ≤ nums[i] ≤ 231 - 1
- -105 ≤ lower ≤ upper ≤ 105
- Watch out for integer overflow - use long long in C++ or long in Java
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code