Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data structure supporting Add and Partial-Sum

Let A[1..n] be an array of real numbers. Design an algorithm to perform any sequence of the following operations:

Add(i,y) -- Add the value y to the ith number.
Partial-sum(i) -- Return the sum of the first i numbers, i.e.

There are no insertions or deletions; the only change is to the values of the numbers. Each operation should take O(logn) steps. You may use one additional array of size n as a work space.

How to design a data structure for above algorithm?

like image 516
Sumer Cip Avatar asked Jan 20 '23 23:01

Sumer Cip


2 Answers

Construct a balanced binary tree with n leaves; stick the elements along the bottom of the tree in their original order.

Augment each node in the tree with "sum of leaves of subtree"; a tree has #leaves-1 nodes so this takes O(n) setup time (which we have).

Querying a partial-sum goes like this: Descend the tree towards the query (leaf) node, but whenever you descend right, add the subtree-sum on the left plus the element you just visited, since those elements are in the sum.

Modifying a value goes like this: Find the query (left) node. Calculate the difference you added. Travel to the root of the tree; as you travel to the root, update each node you visit by adding in the difference (you may need to visit adjacent nodes, depending if you're storing "sum of leaves of subtree" or "sum of left-subtree plus myself" or some variant); the main idea is that you appropriately update all the augmented branch data that needs updating, and that data will be on the root path or adjacent to it.

The two operations take O(log(n)) time (that's the height of a tree), and you do O(1) work at each node.

You can probably use any search tree (e.g. a self-balancing binary search tree might allow for insertions, others for quicker access) but I haven't thought that one through.

like image 170
ninjagecko Avatar answered Jan 22 '23 19:01

ninjagecko


You may use Fenwick Tree

See this question

like image 22
grep Avatar answered Jan 22 '23 19:01

grep