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.
This C solution defines a structure NumArray
that contains the prefix sums array. In the numArrayCreate
function, we allocate memory for the prefix sums and fill it such that each entry in the array contains the cumulative sum up to that index. The numArraySumRange
function then computes the sum of any given range 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.
1class NumArray {
2 private int[] segmentTree;
3 private int n;
4
5 public NumArray(int[] nums) {
6 n = nums.length;
7 segmentTree = new int[4 * n];
8 buildTree(nums, 0, n - 1, 0);
9 }
10
11 private void buildTree(int[] nums, int start, int end, int node) {
12 if (start == end) {
13 segmentTree[node] = nums[start];
14 } else {
15 int mid = start + (end - start) / 2;
16 buildTree(nums, start, mid, 2 * node + 1);
17 buildTree(nums, mid + 1, end, 2 * node + 2);
18 segmentTree[node] = segmentTree[2 * node + 1] + segmentTree[2 * node + 2];
19 }
20 }
21
22 public int sumRange(int left, int right) {
23 return rangeSum(0, n - 1, 0, left, right);
24 }
25
26 private int rangeSum(int start, int end, int node, int left, int right) {
27 if (right < start || end < left) return 0;
28 if (left <= start && end <= right) return segmentTree[node];
29 int mid = start + (end - start) / 2;
30 return rangeSum(start, mid, 2 * node + 1, left, right) +
31 rangeSum(mid + 1, end, 2 * node + 2, left, right);
32 }
33}
The Java solution uses a segment tree to respond to sumRange
queries efficiently. The tree is built on instantiation and queried for the segment sum.