#327

Count of Range Sum

Hard
ArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a modified merge sort algorithm to count the range sums efficiently. By sorting the prefix sums while counting, we can leverage the divide-and-conquer strategy to achieve better performance.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the prefix sums for the array, storing them in a new array.
  2. 2Step 2: Use a recursive function to sort the prefix sums while counting how many of them fall within the specified range [lower, upper].
  3. 3Step 3: For each prefix sum, use binary search to find how many previous sums are within the range when combined with the current prefix sum.
  4. 4Step 4: Return the total count of valid range sums.
solution.py24 lines
1# Full working Python code
2
3def countRangeSum(nums, lower, upper):
4    n = len(nums)
5    prefix_sums = [0] * (n + 1)
6    for i in range(n):
7        prefix_sums[i + 1] = prefix_sums[i] + nums[i]
8    return merge_sort_count(prefix_sums, 0, n, lower, upper)
9
10
11def merge_sort_count(prefix_sums, left, right, lower, upper):
12    if left >= right:
13        return 0
14    mid = (left + right) // 2
15    count = merge_sort_count(prefix_sums, left, mid, lower, upper) + merge_sort_count(prefix_sums, mid + 1, right, lower, upper)
16    j = k = mid + 1
17    for i in range(left, mid + 1):
18        while j <= right and prefix_sums[j] - prefix_sums[i] < lower:
19            j += 1
20        while k <= right and prefix_sums[k] - prefix_sums[i] <= upper:
21            k += 1
22        count += k - j
23    prefix_sums[left:right + 1] = sorted(prefix_sums[left:right + 1])
24    return count

Complexity note: The time complexity is O(n log n) due to the merge sort process, which involves dividing the array and merging it back while counting valid sums. The space complexity is O(n) because we store the prefix sums in a separate array.

  • 1Understanding prefix sums is crucial for efficiently solving range sum problems.
  • 2Using sorting and binary search can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.