Algo-Sim › Advanced Data Structures
Range Sum Query - Mutable (Fenwick Tree)
Medium · Advanced Data Structures · step through it in Java, Python and C++ on your own input
The same queries with one array: tree[i] sums the last (i & −i) values, updates climb with i += i & −i and prefix sums descend with i −= i & −i.
Problem
The same task as the segment tree version, update(index, value) and sumRange(left, right) on a changing array, solved with a Fenwick (binary indexed) tree stored in a single array.
Constraints
- 1 ≤ nums.length ≤ 3 · 10⁴
- -100 ≤ nums[i], value ≤ 100
- Up to 3 · 10⁴ calls in total
- Both operations O(log n)
Edge cases to test
- Index 0 (the tree is 1-indexed)
- A prefix of the whole array
- Negative updates
Follow-up questions
- How do you get a range sum?
prefix(r) − prefix(l − 1): two O(log n) queries.- Can it support range updates?
- Store a difference array in the tree for range add with point query, or two trees for range add with range sum.
Solution
Java
class NumArray {
private final int[] nums, tree;
public NumArray(int[] nums) {
this.nums = nums.clone();
tree = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) add(i + 1, nums[i]);
}
private void add(int i, int delta) {
for (; i < tree.length; i += i & -i) tree[i] += delta;
}
private int prefix(int i) {
int s = 0;
for (; i > 0; i -= i & -i) s += tree[i];
return s;
}
public void update(int index, int val) {
add(index + 1, val - nums[index]);
nums[index] = val;
}
public int sumRange(int left, int right) {
return prefix(right + 1) - prefix(left);
}
}Python
class NumArray:
def __init__(self, nums):
self.nums = nums[:]
self.tree = [0] * (len(nums) + 1)
for i, x in enumerate(nums):
self._add(i + 1, x)
def _add(self, i, delta):
while i < len(self.tree):
self.tree[i] += delta
i += i & -i
def _prefix(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def update(self, index, val):
self._add(index + 1, val - self.nums[index])
self.nums[index] = val
def sumRange(self, left, right):
return self._prefix(right + 1) - self._prefix(left)C++
#include <bits/stdc++.h>
using namespace std;
class NumArray {
public:
vector<int> nums, tree;
NumArray(vector<int> &nums) {
this->nums = nums;
tree = vector<int>(int(nums.size()) + 1);
for (int i = 0; i < int(nums.size()); i++)
add(i + 1, nums[i]);
}
void add(int i, int delta) {
for (; i < int(tree.size()); i += i & -i)
tree[i] += delta;
}
int prefix(int i) {
int s = 0;
for (; i > 0; i -= i & -i)
s += tree[i];
return s;
}
void update(int index, int val) {
add(index + 1, val - nums[index]);
nums[index] = val;
}
int sumRange(int left, int right) {
return prefix(right + 1) - prefix(left);
}
};