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 <vector>
2
3class NumArray {
4public:
5 std::vector<int> prefixSums;
6 NumArray(std::vector<int>& nums) {
7 prefixSums.resize(nums.size() + 1);
8 prefixSums[0] = 0;
9 for (int i = 0; i < nums.size(); ++i) {
10 prefixSums[i + 1] = prefixSums[i] + nums[i];
11 }
12 }
13
14 int sumRange(int left, int right) {
15 return prefixSums[right + 1] - prefixSums[left];
16 }
17};
This C++ solution uses a vector to store prefix sums. The constructor initializes a prefix sums array and fills it accordingly. The sumRange
method returns the required subarray sum using the precomputed prefix sums.
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
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.