Sponsored
Sponsored
The key idea in this approach is to use a prefix sum array. We precompute cumulative sums such that each element at index i
in this prefix array contains the sum of all elements in the nums
array from index 0
to i
. The sum of a subarray can then be computed in constant time using the relation: sumRange(left, right) = prefixSum[right] - prefixSum[left-1]
. This pre-computation allows each query to be answered in O(1) time after O(n) pre-computation.
Time Complexity: O(n) for precomputing the prefix sums, O(1) for each range query.
Space Complexity: O(n) for storing the prefix sums.
1class NumArray:
2 def __init__(self, nums: List[int]):
3 self.prefix_sums = [0]
4 for num in nums:
5 self.prefix_sums.append(self.prefix_sums[-1] + num)
6
7 def sumRange(self, left: int, right: int) -> int:
8 return self.prefix_sums[right + 1] - self.prefix_sums[left]
In this Python implementation, a list called prefix_sums
is initialized to hold cumulative sums. During each call of sumRange
, the range sum is returned using precomputed values.
A Segment Tree is a data structure that allows efficient range query and update operations. It is particularly useful in scenarios where there are multiple queries of the dynamic array that could change over time. For sumRange
queries, the segment tree helps to retrieve the sum in logarithmic time, and it can be further extended to handle updates if needed.
Time Complexity: O(n) for building the tree, O(log n) per query.
Space Complexity: O(n) for the segment tree.
1
This C solution involves a Segment Tree
built in a bottom-up manner. The buildTree
function constructs the tree. During a sumRange
query, the results from relevant nodes are combined. numArrayFree
is used to clean resources.