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.
1#include <stdlib.h>
2
3typedef struct {
4 int* prefixSums;
5 int size;
6} NumArray;
7
8NumArray* numArrayCreate(int* nums, int numsSize) {
9 NumArray* obj = (NumArray*)malloc(sizeof(NumArray));
10 obj->prefixSums = (int*)malloc((numsSize + 1) * sizeof(int));
11 obj->size = numsSize;
12 obj->prefixSums[0] = 0; // Initialize prefix sum for index 0
13 for (int i = 0; i < numsSize; ++i) {
14 obj->prefixSums[i + 1] = obj->prefixSums[i] + nums[i];
15 }
16 return obj;
17}
18
19int numArraySumRange(NumArray* obj, int left, int right) {
20 return obj->prefixSums[right + 1] - obj->prefixSums[left];
21}
22
23void numArrayFree(NumArray* obj) {
24 free(obj->prefixSums);
25 free(obj);
26}
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.
1
Utilizing a segment tree, this JavaScript solution stores partial sums throughout a hierarchical data structure, allowing sumRange
to efficiently obtain a result with logarithmic complexity by combining tree node values.