Given an integer array nums
, handle multiple queries of the following type:
Calculate the sum of the elements of nums
between indices left
and right
inclusive where left
and right
are non-negative integers and left <= right
.
Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer array nums
.int sumRange(int left, int right)
Returns the sum of the elements of nums
between indices left
and right
inclusive (i.e., nums[left] + nums[left + 1] + ... + nums[right]
).Input:
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output:
[null, 1, -1, -3]
Explanation:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1
numArray.sumRange(2, 5); // return -1
numArray.sumRange(0, 5); // return -3
int
type in C++.sumRange
queries?
sumRange
queries are expected. We should optimize for multiple queries after initial preprocessing.left
or right
are out of bounds?
left
and right
are within valid bounds and left <= right
.To efficiently answer the sum queries, we use the concept of prefix sums. This allows us to preprocess the array and then answer any range sum query in constant time O(1)
.
Steps:
prefixSums
where prefixSums[i]
holds the sum of the array from the start up to the i-th index.(left, right)
, the sum can be obtained using prefixSums[right + 1] - prefixSums[left]
.#include <vector>
using namespace std;
class NumArray {
private:
vector<int> prefixSums;
public:
NumArray(vector<int>& nums) {
int n = nums.size();
prefixSums.resize(n + 1, 0);
for (int i = 0; i < n; ++i) {
prefixSums[i + 1] = prefixSums[i] + nums[i];
}
}
int sumRange(int left, int right) {
return prefixSums[right + 1] - prefixSums[left];
}
};
O(n)
where n
is the number of elements in nums
.O(1)
for each sumRange
query.O(n)
for storing the prefix sums.This ensures that after a linear time preprocessing, each range sum query can be answered in constant time, making the overall approach highly efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?