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.
1public class NumArray {
2 private int[] prefixSums;
3 public NumArray(int[] nums) {
4 prefixSums = new int[nums.Length + 1];
5 for (int i = 0; i < nums.Length; i++) {
6 prefixSums[i + 1] = prefixSums[i] + nums[i];
7 }
8 }
9
10 public int SumRange(int left, int right) {
11 return prefixSums[right + 1] - prefixSums[left];
12 }
13}
The C# solution uses an array for prefix sums. Inside the constructor, the prefix sums are computed once. The SumRange
function computes the subarray sum efficiently.
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.