You are given an integer array nums
and are required to implement a data structure that supports two operations:
update(int index, int val)
- Updates the value of nums[index]
to val
.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]
).The nums
array is not immutable, meaning we need to handle multiple update and range sum queries efficiently.
What is the size range of the nums
array?
The size could be in a range of 0 to 30,000.
What are the value ranges of the elements in nums
?
Elements could be in the range of -10^4 to 10^4.
How frequent are update
and sumRange
calls?
Both operations are frequent and need to be optimized.
Could we have multiple updates before a sumRange query? Yes, multiple updates can happen.
Considering the requirement for multiple efficient updates and range sum queries, using a Binary Indexed Tree (also known as Fenwick Tree) will be an effective approach. This allows both update and sum operations in logarithmic time.
BIT
which helps in achieving update and query operations in O(log n) time.class NumArray {
private int[] nums;
private int[] BIT;
private int len;
public NumArray(int[] nums) {
this.nums = nums;
this.len = nums.length;
this.BIT = new int[len + 1];
for (int i = 0; i < len; i++) {
init(i, nums[i]);
}
}
private void init(int index, int val) {
index += 1;
while (index <= len) {
BIT[index] += val;
index += index & -index;
}
}
public void update(int index, int val) {
int delta = val - nums[index];
nums[index] = val;
init(index, delta);
}
private int getSum(int index) {
int sum = 0;
index += 1;
while (index > 0) {
sum += BIT[index];
index -= index & -index;
}
return sum;
}
public int sumRange(int left, int right) {
return getSum(right) - getSum(left - 1);
}
}
n
is the length of nums
.update
operation.sumRange
operation.This solution provides an efficient way to handle dynamic updates and range sum queries which are frequent in this context.
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?