Skip to content

Range Sum Query - Immutable

LeetCode

01 · Question

Given an integer array nums, handle multiple queries of the form sumRange(left, right) returning the sum of elements between left and right inclusive.

02 · Solution

Reference solution

1class NumArray:
2 def __init__(self, nums: List[int]):
3 self.pref = [0]
4 for x in nums:
5 self.pref.append(self.pref[-1] + x)
6
7 def sumRange(self, left: int, right: int) -> int:
8 return self.pref[right + 1] - self.pref[left]