The problem “303. Range Sum Query - Immutable” on LeetCode is defined as follows:
Given an integer array nums, implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums.int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e., nums[left] + nums[left + 1] + ... + nums[right]).nums array be empty?
-10^5 to 10^5.nums array?
10^4.sumRange queries be called?
Given that the array is immutable and we need to support multiple sumRange queries efficiently, we should use a preprocessing approach to create a prefix sum array. This approach will allow us to answer each range sum query in constant time (O(1)).
Steps:
prefix[i] is the sum of the elements from nums[0] to nums[i-1] (with prefix[0] = 0).sumRange(left, right) as prefix[right + 1] - prefix[left].sumRange(left, right) query, use the precomputed prefix sums to get the result in constant time.class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
self.prefix_sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
self.prefix_sums[i + 1] = self.prefix_sums[i] + nums[i]
def sumRange(self, left: int, right: int) -> int:
return self.prefix_sums[right + 1] - self.prefix_sums[left]
nums. This is for building the prefix sum array.sumRange operation is computed using the prefix sums in constant time.This solution efficiently preprocesses the data to allow each range sum query to be answered in constant time, leveraging extra space for the prefix sum array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?