Segment Trees and Fenwick Trees

How segment trees and Fenwick trees answer range queries on changing data in O(log n), when to use each, and what interviewers ask about them.

14 minLesson 2 of 3
On this page
  1. How a segment tree works
  2. How a Fenwick tree works
  3. Choosing between a Fenwick tree and a segment tree
  4. Variants
  5. Pitfalls
  6. In the interview
  7. What to practise next

A segment tree and a Fenwick tree (also called a binary indexed tree) answer range queries, such as the sum of the values from index 2 to index 6, while the values are still being changed. Both handle a query and an update in O(log n) time. You reach for one when a problem mixes many range queries with many updates, and a plain array or a prefix sum array makes one of the two operations too slow.

A prefix sum array answers a range sum in O(1), but changing one value changes every later total, which costs O(n). A plain array has the opposite problem, because an update is O(1) and a range sum is O(n). With a million queries and a million updates either choice is too slow, and these two structures bring each operation down to about 20 steps.

How a segment tree works

A segment tree is a binary tree in which each node stores the sum of a range of the array. The root covers the whole array, each child covers one half of its parent's range, and the leaves cover single values. A query can then be answered by adding a few stored blocks, and an update only has to fix the nodes on the path from one leaf to the root.

The tree is stored in an array in the same way as a heap, so node i has children 2i + 1 and 2i + 2. For the values 5, 2, 6, 3, 1, 4, 7, 2, node 0 covers indexes 0 to 7 (sum 30), node 1 covers 0 to 3 (sum 16), node 2 covers 4 to 7 (sum 14), and the leaves are nodes 7 to 14.

Querying a range

To sum indexes 2 to 6, start at the root and compare each node's range with the query range. If the node's range does not overlap the query at all, the node contributes 0 and its children are not visited. If the node's range lies completely inside the query, the node contributes its stored sum and its children are not visited. If the two ranges overlap only partly, the node asks both of its children and adds their answers.

Sum of indexes 2 to 6Use the arrows or ← → keys
query(node covering lo..hi):  if no overlap with left..right: return 0  if lo..hi is inside left..right: return tree[node]  return query(left child) + query(right child)
  1. segment tree
    301614795952631472
    node range
    0..7
    total
    0

    1The root covers 0..7. The query 2..6 overlaps it only partly, so the root is split.

  2. segment tree
    301614795952631472
    node range
    0..3
    total
    0

    2Node 1 covers 0..3 and also overlaps the query only partly, so it is split.

  3. segment tree
    301614795952631472
    node range
    0..1
    total
    0

    3Node 3 covers 0..1, which is entirely before the query, so it contributes 0 and its children are skipped.

  4. segment tree
    301614795952631472
    node range
    2..3
    total
    9

    4Node 4 covers 2..3, which is fully inside the query, so the total takes its stored value of 9 (6 + 3).

  5. segment tree
    301614795952631472
    node range
    4..7
    total
    9

    5Back at node 2, which covers 4..7, the overlap is partial, so it is split.

  6. segment tree
    301614795952631472
    node range
    4..5
    total
    14

    6Node 5 covers 4..5, which is fully inside the query, so the total adds its 5.

  7. segment tree
    301614795952631472
    node range
    6..7
    total
    14

    7Node 6 covers 6..7. Index 6 is inside the query and index 7 is outside, so the node is split.

  8. segment tree
    301614795952631472
    node range
    6..6
    total
    21

    8Leaf 13 (index 6) is inside the query, so the total adds 7. Leaf 14 (index 7) is outside and adds 0.

  9. segment tree
    301614795952631472
    total
    21
    blocks used
    3

    9The result is 9 + 5 + 7 = 21, taken from three stored blocks.

1 / 9

A query is O(log n) because at each level at most two nodes overlap the query partly, namely the ones that hold the two edges of the range. Every other node on that level is either completely inside or completely outside the query, and those stop at once.

Updating a value

To change one value, replace the leaf and then recompute each ancestor from its two children, walking up to the root. In this example, the value at index 2 was recorded as 6 but should be 11.

Set index 2 to 11Use the arrows or ← → keys
  1. segment tree
    3016147959521131472
    change
    +5

    1Index 2 is stored in leaf 9, and its value changes from 6 to 11.

  2. segment tree
    30161471459521131472
    change
    +5

    2The parent, node 4 (range 2..3), is recomputed as 11 + 3 = 14.

  3. segment tree
    30211471459521131472
    change
    +5

    3Node 1 (range 0..3) is recomputed as 7 + 14 = 21.

  4. segment tree
    35211471459521131472
    nodes updated
    4

    4The root is recomputed as 21 + 14 = 35. Four nodes changed in total, one on each level.

1 / 4

The path from a leaf to the root has one node on each level, so an update is O(log n). The code for building the tree, querying it and updating it follows.

Segment tree for range sums
class SegmentTree {
  constructor(values) {
    this.n = values.length;
    this.tree = new Array(4 * this.n).fill(0);
    if (this.n > 0) this.build(values, 0, 0, this.n - 1);
  }
  build(values, node, lo, hi) {
    if (lo === hi) { this.tree[node] = values[lo]; return; }
    const mid = Math.floor((lo + hi) / 2);
    this.build(values, 2 * node + 1, lo, mid);
    this.build(values, 2 * node + 2, mid + 1, hi);
    this.tree[node] = this.tree[2 * node + 1] + this.tree[2 * node + 2];
  }
  // Sum of values[left..right], both included.
  query(left, right, node = 0, lo = 0, hi = this.n - 1) {
    if (right < lo || hi < left) return 0;                 // no overlap
    if (left <= lo && hi <= right) return this.tree[node]; // fully inside
    const mid = Math.floor((lo + hi) / 2);
    return this.query(left, right, 2 * node + 1, lo, mid) +
           this.query(left, right, 2 * node + 2, mid + 1, hi);
  }
  // Set values[index] = value.
  update(index, value, node = 0, lo = 0, hi = this.n - 1) {
    if (lo === hi) { this.tree[node] = value; return; }
    const mid = Math.floor((lo + hi) / 2);
    if (index <= mid) this.update(index, value, 2 * node + 1, lo, mid);
    else this.update(index, value, 2 * node + 2, mid + 1, hi);
    this.tree[node] = this.tree[2 * node + 1] + this.tree[2 * node + 2];
  }
}
class SegmentTree:
    def __init__(self, values):
        self.n = len(values)
        self.tree = [0] * (4 * self.n)
        if self.n > 0:
            self._build(values, 0, 0, self.n - 1)
 
    def _build(self, values, node, lo, hi):
        if lo == hi:
            self.tree[node] = values[lo]
            return
        mid = (lo + hi) // 2
        self._build(values, 2 * node + 1, lo, mid)
        self._build(values, 2 * node + 2, mid + 1, hi)
        self.tree[node] = self.tree[2 * node + 1] + self.tree[2 * node + 2]
 
    def query(self, left, right, node=0, lo=0, hi=None):
        """Sum of values[left..right], both included."""
        if hi is None:
            hi = self.n - 1
        if right < lo or hi < left:
            return 0                      # no overlap
        if left <= lo and hi <= right:
            return self.tree[node]        # fully inside
        mid = (lo + hi) // 2
        return (self.query(left, right, 2 * node + 1, lo, mid) +
                self.query(left, right, 2 * node + 2, mid + 1, hi))
 
    def update(self, index, value, node=0, lo=0, hi=None):
        """Set values[index] = value."""
        if hi is None:
            hi = self.n - 1
        if lo == hi:
            self.tree[node] = value
            return
        mid = (lo + hi) // 2
        if index <= mid:
            self.update(index, value, 2 * node + 1, lo, mid)
        else:
            self.update(index, value, 2 * node + 2, mid + 1, hi)
        self.tree[node] = self.tree[2 * node + 1] + self.tree[2 * node + 2]

Nothing in this code is specific to sums. If the combine step is a minimum and the answer for an empty overlap is infinity instead of 0, the same tree answers range minimum queries. Any operation that gives the same result however the values are grouped can be used, such as sum, minimum, maximum, greatest common divisor or bitwise AND.

How a Fenwick tree works

For sums, a Fenwick tree gives the same O(log n) bounds with less code and less memory. It is a single array of n + 1 numbers with two short loops, and it has no explicit tree.

The slots are numbered from 1. Slot i stores the sum of the last lowbit(i) items that end at item i, where lowbit(i) is the lowest 1 bit of i, computed as i & -i (see Bit Manipulation). Slot 6 is 110 in binary, so its lowest bit is 2 and it holds items 5 and 6. Slot 7 holds only item 7, and slot 8 holds all eight items.

1 2 3 4 5 6 7 8 5 2 6 3 1 4 7 2 items t1=5 t3=6 t5=1 t7=7 t2=7 t6=5 t4=16 t8=30 first 7 items: 7 + 5 + 16 = 28
Each slot covers a block of items that ends at the slot&#39;s own position. The total of the first 7 items is read from slots 7, 6 and 4.

To get the total of the first i items, add slot i, then move to slot i − lowbit(i), and repeat until the slot is 0. For 7 the slots are 7, 6 and 4. Each step removes the lowest 1 bit, so the loop runs at most about log₂(n) times.

To add a value to item i, add it to slot i, then move to slot i + lowbit(i), which is the next larger block that also covers item i, and repeat while the slot is inside the array. For item 3 the slots are 3, 4 and 8. This loop also runs at most about log₂(n) times. The trace below adds 5 to item 3 and then totals the first 7 items.

Fenwick tree: add 5 to item 3, then total the first 7Use the arrows or ← → keys
add(i, delta): while i <= n: t[i] += delta; i += i & -ifirst(i): s = 0; while i > 0: s += t[i]; i -= i & -i
  1. t
    0
    15
    27
    36
    416
    51
    65
    77
    830
    i
    none

    1The slots for the values 5, 2, 6, 3, 1, 4, 7, 2. Slot 0 is not used.

  2. t
    0
    15
    27
    311i
    416
    51
    65
    77
    830
    i
    3

    2Add 5 to item 3. Slot 3 changes from 6 to 11, and because lowbit(3) is 1 the next slot is 4.

  3. t
    0
    15
    27
    311
    421i
    51
    65
    77
    830
    i
    4

    3Slot 4 covers items 1 to 4, so it changes from 16 to 21. Because lowbit(4) is 4, the next slot is 8.

  4. t
    0
    15
    27
    311
    421
    51
    65
    77
    835i
    i
    8

    4Slot 8 changes from 30 to 35. The next slot would be 16, which is past the end, so the update stops after changing three slots.

  5. t
    0
    15
    27
    311
    421
    51
    65
    77i
    835
    i
    7
    s
    7

    5Now total the first 7 items. Slot 7 holds item 7 alone, so s is 7, and because lowbit(7) is 1 the next slot is 6.

  6. t
    0
    15
    27
    311
    421
    51
    65i
    77
    835
    i
    6
    s
    12

    6Slot 6 holds items 5 and 6, so s becomes 7 + 5 = 12, and because lowbit(6) is 2 the next slot is 4.

  7. t
    0i
    15
    27
    311
    421
    51
    65
    77
    835
    i
    0
    s
    33

    7Slot 4 holds items 1 to 4, so s becomes 12 + 21 = 33, and the next slot is 0, which ends the loop. Adding the items directly gives 5 + 2 + 11 + 3 + 1 + 4 + 7 = 33 as well.

1 / 7

The code uses 0-based indexes and shifts them by one inside the class. The sum of left..right is first(right + 1) − first(left), which is the same subtraction that prefix sums use.

Fenwick tree
class Fenwick {
  constructor(n) { this.t = new Array(n + 1).fill(0); }
  add(index, delta) { // values[index] += delta
    for (let i = index + 1; i < this.t.length; i += i & -i) this.t[i] += delta;
  }
  first(count) { // sum of the first count values
    let s = 0;
    for (let i = count; i > 0; i -= i & -i) s += this.t[i];
    return s;
  }
  rangeSum(left, right) { return this.first(right + 1) - this.first(left); }
}
 
const fw = new Fenwick(8);
[5, 2, 6, 3, 1, 4, 7, 2].forEach((v, i) => fw.add(i, v));
fw.add(2, 5);
fw.first(7);       // 33
fw.rangeSum(2, 6); // 26
class Fenwick:
    def __init__(self, n):
        self.t = [0] * (n + 1)
 
    def add(self, index, delta):  # values[index] += delta
        i = index + 1
        while i < len(self.t):
            self.t[i] += delta
            i += i & -i
 
    def first(self, count):  # sum of the first count values
        s, i = 0, count
        while i > 0:
            s += self.t[i]
            i -= i & -i
        return s
 
    def range_sum(self, left, right):
        return self.first(right + 1) - self.first(left)
 
fw = Fenwick(8)
for i, v in enumerate([5, 2, 6, 3, 1, 4, 7, 2]):
    fw.add(i, v)
fw.add(2, 5)
fw.first(7)        # 33
fw.range_sum(2, 6) # 26
ApproachTimeSpaceWhy
Plain arrayO(1) update, O(n) queryO(1)Every range sum is a loop over the range.
Prefix sumsO(n) update, O(1) queryO(n)A change shifts every later total.
Segment treeO(log n) bothO(n)An update touches one node per level, and a query visits at most two partly overlapping nodes per level. Building the tree is O(n).
Fenwick treeO(log n) bothO(n)Each loop step removes or carries one bit of the slot number. Building by n separate adds is O(n log n).

Choosing between a Fenwick tree and a segment tree

Use a Fenwick tree when the query is a sum or a count. It is shorter to write, it needs n + 1 numbers instead of up to 4n, and it is faster in practice. Its range query subtracts one prefix total from another, so it only fits operations that can be undone. Sum and count qualify. Minimum and maximum do not, because knowing the minimum of the first 7 items and of the first 2 items says nothing about the minimum of items 3 to 7.

Use a segment tree for minimum, maximum, greatest common divisor, or any other operation that cannot be subtracted.

Variants

Range updates with lazy propagation

Sometimes an update applies to a whole range, such as "add 3 to every value from index 2 to 6". A segment tree can do it in O(log n) with lazy propagation. When an update covers a node's whole range, the node changes its own stored sum and records the pending addition, without touching its children. The pending addition is passed down to the children only when a later query or update has to go below that node. Forgetting to push the pending addition down before visiting the children gives stale sums.

Counting with a Fenwick tree

A Fenwick tree is also used to count items, which covers a common family of problems such as counting how many earlier values are smaller than the current one, or counting inversions in an array. The tree stores a count for each possible value. For each element you ask for the number of stored values below it, which is a prefix query, and then add 1 at the element's own position. If the values are large, first replace each one by its rank among the sorted distinct values, which is called coordinate compression.

When neither structure is needed

If the values never change, use prefix sums for range sums, because they are simpler and answer in O(1). If the problem asks for something that is not a range aggregate, such as the k-th smallest value in a range, these trees do not solve it in their basic form.

Pitfalls

In the interview

The signal is a problem that gives you an array and a long list of operations that mix changes to single values with queries about ranges, such as sums, minimums or counts. If all the queries come after all the updates, or there are no updates, a prefix sum array is enough. When both kinds of operation are frequent and a loop over the range would be too slow, say that you need O(log n) for each and choose between a Fenwick tree and a segment tree. For sums choose the Fenwick tree, and for minimum or maximum choose the segment tree.

Interviewers commonly follow up with these questions.

  • "Why is a query O(log n)?" At each level at most two nodes overlap the query range partly, and those are the nodes that hold the edges of the range. Every other node on that level is either fully inside, so it returns a stored sum, or fully outside, so it returns nothing. The tree has about log₂(n) levels.
  • "Can a Fenwick tree find a range minimum?" No. The range query subtracts two prefix results, and a minimum cannot be subtracted. Use a segment tree instead.
  • "How would you add a value to every element in a range?" Use a segment tree with lazy propagation. A node whose range is completely covered records the pending addition and updates its own sum, and the addition is pushed to the children only when a later operation needs to go below that node. Updates and queries both stay O(log n).
  • "How do you build the structure from an initial array?" A segment tree is built recursively in O(n), because each node is computed once from its two children. A Fenwick tree built by n separate adds costs O(n log n), but it can be built in O(n) by copying the array into the slots and then, for each slot i, adding its value to slot i + lowbit(i) if that slot exists.
Quick check

In a segment tree over 1,000,000 values, about how many nodes change on one update?

Which Fenwick slots does the query for the total of the first 6 items read?

You need the smallest value in any range, and the values keep changing. Which structure fits?

What to practise next

Change the segment tree to answer range minimums and check it by hand on the numbers above. Then read Designing Data Structures, which covers combining simple structures to meet several cost targets at once.