04. Count of Range Sum

Difficulty:HardPattern:Prefix Sum + Merge SortTime:O(n log n)Space:O(n)

Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.

How It Works & Algorithmic Design

Solves using Prefix Sum Array + Modified Merge Sort:

  1. Prefix Sum Array: P[i] = P[i-1] + nums[i-1] for $0 \le i \le n$.
  2. Merge Sort Function countWhileMergeSort(left, right):
    • Divide P into left and right halves.
    • For each element $P[i]$ in left half, find two pointers $j$ and $k$ in right half such that $P[j] - P[i] \ge \text{lower}$ and $P[k] - P[i] > \text{upper}$.
    • Accumulate valid range count: count += (k - j).
    • Perform standard merge step to keep prefix sub-array sorted.

Why This Approach Works Best

Evaluates prefix sum pairs across splits in $O(n \log n)$ time.

Example Walkthrough

Input

nums = [-2, 5, -1], lower = -2, upper = 2

Target range [-2, 2].

Valid Ranges

Range sums [-2], [1], [2] lie in [-2, 2].

3 valid ranges.

Output

3

Matching count.

Answer: Count of Range Sum implementation

function countRangeSum(nums, lower, upper) {
  const n = nums.length;
  const P = new Array(n + 1).fill(0);
  for (let i = 0; i < n; i++) P[i + 1] = P[i] + nums[i];
  function mergeSort(left, right) {
    if (right - left <= 1) return 0;
    const mid = Math.floor((left + right) / 2);
    let count = mergeSort(left, mid) + mergeSort(mid, right);
    let j = mid, k = mid;
    for (let i = left; i < mid; i++) {
      while (j < right && P[j] - P[i] < lower) j++;
      while (k < right && P[k] - P[i] <= upper) k++;
      count += k - j;
    }
    const sorted = [];
    let l = left, r = mid;
    while (l < mid && r < right) {
      if (P[l] <= P[r]) sorted.push(P[l++]);
      else sorted.push(P[r++]);
    }
    while (l < mid) sorted.push(P[l++]);
    while (r < right) sorted.push(P[r++]);
    for (let i = 0; i < sorted.length; i++) P[left + i] = sorted[i];
    return count;
  }
  return mergeSort(0, n + 1);
}

Count prefix sum differences within [lower, upper] boundaries using two pointers during Merge Sort.

Key Takeaways
  • Converts range sums to prefix differences $P[j] - P[i]$.

  • Pointers $j$ and $k$ move monotonically during merge sort.

  • Optimal execution time $O(n \log n)$.