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 private int[] segmentTree;
private int n;
public NumArray(int[] nums) {
n = nums.Length;
segmentTree = new int[4 * n];
BuildTree(nums, 0, n - 1, 0);
}
private void BuildTree(int[] nums, int start, int end, int node) {
if (start == end) {
segmentTree[node] = nums[start];
} else {
int mid = (start + end) / 2;
BuildTree(nums, start, mid, 2 * node + 1);
BuildTree(nums, mid + 1, end, 2 * node + 2);
segmentTree[node] = segmentTree[2 * node + 1] + segmentTree[2 * node + 2];
}
}
public int SumRange(int left, int right) {
return RangeSum(0, n - 1, 0, left, right);
}
private int RangeSum(int start, int end, int node, int left, int right) {
if (right < start || end < left) return 0;
if (left <= start && end <= right) return segmentTree[node];
int mid = (start + end) / 2;
return RangeSum(start, mid, 2 * node + 1, left, right) +
RangeSum(mid + 1, end, 2 * node + 2, left, right);
}
}
C#-based implementation leverages segment trees to break down query problems into simpler subproblems, recombining solutions to form an answer to the SumRange
function.