Problem Description
Given an integer array nums and two integers lower and upper, count the number of range sums S(i, j) (the sum of elements from index i to j inclusive, where i ≤ j) that lie within the inclusive range [lower, upper].
Key Insights
- Transform the problem using prefix sums. Define prefix[i] as the sum of elements nums[0] to nums[i-1] which simplifies S(i, j) to prefix[j+1] - prefix[i].
- The problem then reduces to counting, for every prefix[j+1], how many earlier prefix[i] satisfy: lower ≤ prefix[j+1] - prefix[i] ≤ upper.
- Use a modified merge sort (or other data structures like Binary Indexed Tree or Segment Tree) to count the number of valid pairs while sorting the prefix sum array.
- The merge step cleverly counts the number of valid prefix differences before merging two sorted halves.
Space and Time Complexity
Time Complexity: O(n log n) due to merge sort style divide and conquer. Space Complexity: O(n) for the prefix sum and temporary arrays used in merging.
Solution
We transform the input array nums into a prefix sum array. For each new prefix sum, we search the sorted list of previous prefix sums to count how many fall into the range [current - upper, current - lower]. This is efficiently done during the merge sort process where each merge step counts the valid pairs between the two sorted subarrays. The merge sort guarantees that the array segments are sorted, which allows binary-counting of valid ranges by maintaining two pointers. This approach eliminates the need for nested loops and achieves O(n log n) complexity.