Skip to content
Problem 327 · LeetCode 327(opens in a new tab)

Count of Range Sum

HardDivide and conquer

You get a list of whole numbers, nums, plus two bounds, lower and upper. A range is a run of consecutive positions i to j with i ≤ j, and its sum is nums[i] + … + nums[j].

Count how many ranges have a sum between lower and upper, both ends included. A single number is a range too.

Example 1

Input:  nums = [3, -4, 2], lower = -1, upper = 2
Output: 3
Why:    3 + (-4) = -1, 3 + (-4) + 2 = 1, and 2 alone
2 more examples and the constraints

Example 2

Input:  nums = [-7], lower = -10, upper = -5
Output: 1
Why:    the only range is [-7], and -7 is in range

Example 3

Input:  nums = [1, 1, 1], lower = 2, upper = 2
Output: 2
Why:    the two ranges of length 2 sum to 2

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • −100,000 ≤ lower ≤ upper ≤ 100,000
  • The answer fits in a 32-bit integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every range, running sumO(n²)
  2. Prefix sums + merge sortO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Every range, running sumO(n²)
Too slow at the limit
Prefix sums + merge sortO(n log n)
Best; the standard answer

n = length of nums.

Edge cases to test

  • Single number. [-7] with [-10, -5] gives 1; a range can be one element.
  • All zeros. [0, 0, 0, 0] with [0, 0]: every one of the 10 ranges counts.
  • Huge values. Sums of numbers near 2³¹ overflow 32-bit ints; keep prefix sums in 64 bits.
  • Nothing in range. [5, 6] with [-3, -1] gives 0.

Common mistakes

  • Forgetting pre[0] = 0, which drops every range that starts at index 0.
  • Storing prefix sums in 32-bit ints, which wraps around for large inputs.
  • Restarting the pointers a and b for each left value, which brings back O(n²) inside each merge.

How to talk through it

  1. 1Clarify. Are both ends included? Can values be negative? How large can the sums get?
  2. 2Give the brute force. Every start, running total to every end: O(n²), about 5 billion steps at the limit.
  3. 3Rewrite with prefix sums. A range sum is pre[j] − pre[i]; now count pairs with the difference in range.
  4. 4Count during merge sort. Both halves sorted means each left value's partners form one block; two pointers find it.
  5. 5Test out loud. Run a single number, all zeros, and values near 2³¹ to check the overflow.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?