Range Sum Query - Immutable

LeetCode

LeetCode: https://leetcode.com/problems/range-sum-query-immutable/

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

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]
i
0
0
nums=[-2, 0, 3, -5, 2, -1]
Step 1 / 6
Step 1:
Build pref where pref[i] = sum of nums[0..i-1]. Start with pref[0]=0.
Pointers: i=0
Focus: select @ [0]