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 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
Array: [-2, 5, -1]-25-1Original Array0-232Prefix SumsValid range sums in [-2, 2]:• Range [0,0]: sum = -2 ✓• Range [2,2]: sum = -1 ✓• Range [0,2]: sum = 2 ✓Result: 3 valid range sums
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

n
2n
Quadratic Growth
Space Complexity
O(n)

Space for prefix sums and sorted list of previous prefix sums

n
2n
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
Asked in
Google 45 Amazon 32 Microsoft 28 Meta 22
52.0K Views
Medium Frequency
~35 min Avg. Time
1.8K 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