Count of Range Sum solution explained
Count of Range Sum asks how many contiguous subarrays have a sum between lower and upper, both inclusive. Rewrite every subarray sum as a difference of two prefix sums, P[j] - P[i] with i < j, so the task becomes counting pairs of prefix sums whose difference falls in [lower, upper]. Merge sort over the prefix array counts those pairs in O(n log n): before merging two sorted halves, slide two pointers through the right half to count, for each left value, how many right values land in its window. A Fenwick tree over compressed prefix values reaches the same bound.
By Evin JohnPublished 9 min read
The problem, restated
You get an integer array, which may contain negative numbers, and two integers lower and upper. Count the non-empty contiguous subarrays whose sum is at least lower and at most upper. Two subarrays with the same values but different positions count separately.
| nums | lower, upper | Count | Note |
|---|---|---|---|
| [3, -1, 2] | 1, 3 | 4 | [3], [3, -1], [-1, 2], [2] |
| [0, 0] | 0, 0 | 3 | Both single zeros and the pair |
| [-2, 4, -2] | 0, 0 | 1 | Only the whole array sums to 0 |
| [5] | 6, 10 | 0 | Nothing reaches 6 |
| [1, 2, 3] | 4, 2 | 0 | lower above upper: an empty window |
What the interviewer is checking
There are two steps, and interviewers grade both. The first is the reduction: subarray sums are differences of prefix sums, and including the leading 0 is what lets subarrays that start at index 0 be counted. The second is recognizing that counting pairs under an order condition is the same family as counting inversions, which merge sort or a Fenwick tree solves in O(n log n). Negative numbers rule out a sliding window, and a good candidate says so before anyone asks.
Why a sliding window does not work
A window that grows and shrinks relies on sums only rising when you add an element. With negative values, extending a window can lower its sum, so there is no rule for when to move the left edge. That is the signal to switch to prefix sums and a counting structure.
Brute force with prefix sums
def count_range_sum_slow(nums, lower, upper):
pre = [0]
for x in nums:
pre.append(pre[-1] + x)
count = 0
for j in range(1, len(pre)):
for i in range(j):
if lower <= pre[j] - pre[i] <= upper:
count += 1
return countEach subarray nums[i..j - 1] is pre[j] - pre[i]. The double loop is the honest first answer. It also shows the interviewer the exact pair condition that the faster version will count.
Merge sort over prefix sums
Sort the prefix array with merge sort, and count pairs at each merge. When the two halves are each sorted, every left element has a smaller original index than every right element, so any left value a and right value b form a valid pair when lower <= b - a <= upper. For a fixed a, the matching b values are a contiguous block of the sorted right half: from the first b >= a + lower to the last b <= a + upper. As a grows, both block edges only move forward, so two pointers count all left elements in one pass over the right half.
def count_range_sum(nums, lower, upper):
if lower > upper:
return 0
pre = [0]
for x in nums:
pre.append(pre[-1] + x)
def solve(lo, hi):
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
total = solve(lo, mid) + solve(mid, hi)
start = end = mid
for i in range(lo, mid):
while start < hi and pre[start] - pre[i] < lower:
start += 1
while end < hi and pre[end] - pre[i] <= upper:
end += 1
total += end - start
merged = []
a, b = lo, mid
while a < mid and b < hi:
if pre[a] <= pre[b]:
merged.append(pre[a])
a += 1
else:
merged.append(pre[b])
b += 1
merged.extend(pre[a:mid])
merged.extend(pre[b:hi])
pre[lo:hi] = merged
return total
return solve(0, len(pre))function countRangeSum(nums, lower, upper) {
if (lower > upper) return 0;
const pre = [0];
for (const x of nums) pre.push(pre[pre.length - 1] + x);
function solve(lo, hi) {
if (hi - lo <= 1) return 0;
const mid = (lo + hi) >> 1;
let total = solve(lo, mid) + solve(mid, hi);
let start = mid;
let end = mid;
for (let i = lo; i < mid; i++) {
while (start < hi && pre[start] - pre[i] < lower) start++;
while (end < hi && pre[end] - pre[i] <= upper) end++;
total += end - start;
}
const merged = [];
let a = lo;
let b = mid;
while (a < mid && b < hi) {
if (pre[a] <= pre[b]) merged.push(pre[a++]);
else merged.push(pre[b++]);
}
while (a < mid) merged.push(pre[a++]);
while (b < hi) merged.push(pre[b++]);
for (let k = 0; k < merged.length; k++) pre[lo + k] = merged[k];
return total;
}
return solve(0, pre.length);
}The counting loop runs before the merge, while each half is still separately sorted and the left-right split still means "earlier" and "later". Counting after merging would mix the halves and lose that meaning.
Trace on [3, -1, 2] with bounds 1 and 3
The prefix array is [0, 3, 2, 4]. The first split is [0, 3] and [2, 4]. Inside [0, 3], the pair 0 then 3 gives a difference of 3, which counts. Inside [2, 4], the difference 2 counts. Now both halves are sorted: left [0, 3], right [2, 4]. For left value 0, the right values with a difference from 1 to 3 are 2 only (4 is too far), adding 1. For left value 3, the differences are -1 and 1, so only 4 counts, adding 1. The total is 1 + 1 + 1 + 1 = 4, matching the table.
Fenwick tree alternative
Scan the prefix sums left to right. For the current P[j], the earlier prefixes that pair with it are those in [P[j] - upper, P[j] - lower]. Keep a Fenwick tree of counts over the sorted distinct prefix values, use binary search to turn the window into a range of positions, and query. Then add P[j]. Start with P[0] = 0 already in the tree.
from bisect import bisect_left, bisect_right
def count_range_sum_bit(nums, lower, upper):
if lower > upper:
return 0
pre = [0]
for x in nums:
pre.append(pre[-1] + x)
vals = sorted(set(pre))
fen = [0] * (len(vals) + 1)
def bump(pos):
while pos <= len(vals):
fen[pos] += 1
pos += pos & -pos
def upto(pos):
s = 0
while pos > 0:
s += fen[pos]
pos -= pos & -pos
return s
total = 0
bump(bisect_left(vals, pre[0]) + 1)
for p in pre[1:]:
lo_pos = bisect_left(vals, p - upper)
hi_pos = bisect_right(vals, p - lower)
total += upto(hi_pos) - upto(lo_pos)
bump(bisect_left(vals, p) + 1)
return totalbisect_left gives the number of stored values below the window and bisect_right the number at or below its top, so their Fenwick prefix counts differ by exactly the values inside. A window that lies entirely between two stored values yields equal positions and adds zero. An inverted window, with lower above upper, would make the top position smaller than the bottom one and subtract, which is why both fast versions return 0 for it up front.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Sum every subarray directly | O(n³), or O(n²) with a running sum | O(1) |
| Prefix sums, every pair | O(n²) | O(n) |
| Merge sort with two pointers | O(n log n) | O(n) |
| Fenwick tree over compressed prefixes | O(n log n) | O(n) |
Overflow and number size
Prefix sums can exceed 32-bit range even when every element fits, so use 64-bit integers in C++ or Java. In Python integers grow as needed. JavaScript numbers are exact for integers up to 2^53 - 1; as a rough check, a few hundred thousand values of about 2 × 10^9 each sum to under 10^15, which is inside that limit, but larger inputs would call for BigInt.
Edge cases
- Subarrays starting at index 0: they need P[0] = 0 in the prefix array.
- lower equal to upper, which tests the inclusive comparison on both sides.
- lower greater than upper: the answer is 0. Without an early return, the end pointer can stop before the start pointer and the count goes negative; on [1, 2, 3] with bounds 4 and 2 the unguarded merge sort returns -2.
- All zeros with bounds 0 and 0: every one of the n(n + 1) / 2 subarrays counts.
- Large positive and negative values that would overflow 32-bit sums.
Common mistakes
- Leaving out the 0 at the start of the prefix array, which drops every subarray that begins at the first element.
- Counting after the merge instead of before it, which pairs elements with earlier ones from the same side.
- Resetting the two pointers for each left element, which brings back O(n²) inside each merge.
- Skipping the lower > upper check. The brute force quietly returns 0, but the pointer and Fenwick versions subtract and can return a negative count.
- Using a sliding window, which fails as soon as a negative number appears.
- Querying a Fenwick tree for [P[j] + lower, P[j] + upper] instead of [P[j] - upper, P[j] - lower] when scanning left to right.
How to explain it out loud
Fictional example
- Candidate
- Values can be negative, so a sliding window will not work. I will use prefix sums with a leading zero. A subarray sum is P[j] minus P[i] with i less than j, so I am counting pairs whose difference is between lower and upper.
- Candidate
- That is like counting inversions with a window instead of a single comparison. In merge sort, every left element comes before every right element. For each left value, the matching right values form one block in the sorted right half, and the block edges only move forward, so two pointers count everything in linear time per merge.
- Candidate
- Total O(n log n). I would use 64-bit sums in a typed language.
Related problems
Reverse Pairs uses the same count-then-merge structure with a different pair condition. Count of Smaller Numbers After Self counts per position rather than in total and is a good Fenwick tree warm-up. Data Stream as Disjoint Intervals and Range Module are about keeping sorted data while it changes, the other skill this problem leans on.
Practicing with Natively
The leap from subarrays to prefix pairs is the part most worth rehearsing, because once it is said clearly the rest follows. Try it in a mock round on Mac or Windows with Natively transcribing, and read back how long it took you to get there. After your own attempt, Natively can read the problem from a screenshot and propose an approach, such as the Fenwick version, to compare with your merge sort. More on the AI interview assistant.
Questions people ask
How do you solve Count of Range Sum?
Build prefix sums with a leading 0, so each subarray sum is P[j] - P[i] with i < j. Merge sort the prefix array and, before each merge, count left values a with right values b in [a + lower, a + upper] using two pointers.
Why can't I use a sliding window for Count of Range Sum?
The array can contain negative numbers, so extending a window can lower its sum. There is no monotonic rule for moving the window's edges.
What is the time complexity of Count of Range Sum?
O(n log n) time and O(n) memory with merge sort or a Fenwick tree over compressed prefix sums. Checking every pair of prefix sums is O(n squared).
What if lower is greater than upper?
Return 0 right away. The pointer and Fenwick versions would otherwise subtract and can report a negative count.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
