LeetCode 303: Range Sum Query – Immutable

link

We can compute prefix sums in the beginning.

OperationTimeSpace
__init__\mathcal{O}(n)\mathcal{O}(n)
sumRange\mathcal{O}(1)\mathcal{O}(1)
class NumArray:

    def __init__(self, nums: List[int]):
        self.prefix_sums = [0] * len(nums)
        self.prefix_sums[0] = nums[0]
        for i in range(1, len(nums)):
            self.prefix_sums[i] = self.prefix_sums[i-1] + nums[i]

    def sumRange(self, left: int, right: int) -> int:
        left_sum = self.prefix_sums[left-1] if left > 0 else 0
        return self.prefix_sums[right] - left_sum


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)

Leave a comment