Skip to content

327. Count Of Range Sum

Array Binary Search Divide and Conquer Binary Indexed Tree Segment Tree Merge Sort Ordered Set

Problem - Count Of Range Sum

Hard

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

Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.

 

Example 1:

Input: nums = [-2,5,-1], lower = -2, upper = 2
Output: 3
Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.

Example 2:

Input: nums = [0], lower = 0, upper = 0
Output: 1

 

Constraints:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • -105 <= lower <= upper <= 105
  • The answer is guaranteed to fit in a 32-bit integer.

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
        n = list(accumulate(nums, initial=0))
        sorted_array = sorted(set(val for x in n for val in (x, x - lower, x - upper)))
        tree = BinaryIndexedTree(len(sorted_array))
        result = 0

        for x in n:
            left = bisect_left(sorted_array, x - upper) + 1
            right = bisect_left(sorted_array, x - lower) + 1
            result += tree.query(right) - tree.query(left - 1)
            tree.update(bisect_left(sorted_array, x) + 1, 1)

        return result

class BinaryIndexedTree:
    def __init__(self, n):
        self.n = n
        self.tree = [0] * (n + 1)

    def update(self, x, v):
        while x <= self.n:
            self.tree[x] += v
            x += x & -x

    def query(self, x):
        result = 0
        while x > 0:
            result += self.tree[x]
            x -= x & -x
        return result

Submission Stats:

  • Runtime: 1701 ms (22.25%)
  • Memory: 52.4 MB (38.67%)