# Daily Archives: January 12, 2016

## Binary Indexed Tree

https://leetcode.com/problems/range-sum-query-mutable/

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

This problem can be surely solved by segment tree. However, another approach is to use binary indexed tree. Binary indexed tree also provides O(logN) time for lookup, O(logN) update. But it is easier to implement and takes O(N) storage.

Let’s start by talking about a bit operation. For example, if we have a = 00110100 in binary, and we want to get the as much as zero from right until it reaches the 1st 1, which is 100. We can do (-a) & a. It is because in machine, all number uses complement form. It has below calculation:
complement of a:   00110100
complement of -a:  11001100
So (-a) & a = 100

Let’s see an example of binary indexed tree for index 1 to 15. Assume we built an binary indexed tree for nums[] array. In this tree structure, take 1011(11) as example. The value of tree contains nums. In order to get the rangeSum(1, 11), we just add value of its ancestry: tree + tree + tree.

tree contains nums, nums; tree contains value nums, nums, nums,…,nums.

rangeSum(1, 11) = tree + tree + tree.

Another example, rangeSum(1, 7) = tree + tree + tree

So, we can find the rule for sum:

```while (idx > 0) {
sum += tree[idx];
idx -= (-idx) & idx;
}```

Let’s talk about how do we updat. Let’s say we increase 2 to nums. Then we should increase 2 to tree, tree, tree. Another example, we want to add 2 to nums, then we need to add 2 to tree, tree, tree. So we can find the rule for increase a value to nums[idx]:

```while (idx <= n) {
tree[idx] += val;
idx += (-idx) & idx;
}```

check my code on github: link