Skip to main content

Binary Indexed Tree

SpaceTime
AccessLookupInsertionDeletion
O(n)O(log n)O(log n)O(log n)O(log n)

Definition​

Binary Indexed Tree is a data structure that allows efficient updates and range queries on an array. It is built by storing the cumulative sums of the array elements in a binary tree, allowing for efficient computation of prefix sums and range queries.

Simplified

It's like a smart organizer at a party. It quickly updates or calculates the total of a series of numbers (like candies held by people), saving a lot of time.

Practice​

AspectPseudo Code
Increase
increase(position, value):
if position < 1 or position > tree_array.length:
'Position is out of allowed range'
for i in range(position, tree_array.length + 1, i & -i):
tree_array[i] += value
Query
query(position):
if position < 1 or position > tree_array.length:
'Position is out of allowed range'
sum = 0
for i in range(position, 0, -(i & -i)):
sum += tree_array[i]
return sum
Query Range
query_range(left_index, right_index):
if left_index > right_index:
'Left index cannot be greater than right one'
if left_index == 1:
return query(right_index)
return query(right_index) - query(left_index - 1)

query(position):
if position < 1 or position > tree_array.length:
'Position is out of allowed range'
sum = 0
for i in range(position, 0, -(i & -i)):
sum += tree_array[i]
return sum