Segment Trees & Fenwick Trees

Answer range queries (sum, min, max) and apply updates in O(log n) — the structures behind range-query problems.

Advanced 2 min readLesson 14 of 16 Interview Q&A

Prefix sums answer "sum of a[l..r]" in O(1) — until the array changes, which costs O(n) to rebuild. When you need both range queries and point updates, use a Fenwick tree or a segment tree: both do each in O(log n).

StructureQueryUpdateBuildSupports
Plain arrayO(n)O(1)—anything
Prefix sumsO(1)O(n)O(n)invertible ops (sum, xor)
Fenwick tree (BIT)O(log n)O(log n)O(n)sums / invertible ops
Segment treeO(log n)O(log n)O(n)any associative op: sum, min, max, gcd…

Segment tree

A binary tree where each node stores the answer (say, the sum) for a segment of the array. The root covers [0, n−1]; each node splits its range in half.

134 [0-1]59 [0-2]7916 [3-4]1127 [3-5]36 [0-5]
Segment tree over [1, 3, 5, 7, 9, 11] storing sums.

A query [l, r] decomposes into at most ~2 log n fully-covered nodes. An update changes one leaf and the log n ancestors above it. Stored in an array of size 4n (or 2n for the iterative version).

class SegmentTree {
    private final int n;
    private final int[] t;

    SegmentTree(int[] a) {
        n = a.length;
        t = new int[2 * n];
        for (int i = 0; i < n; i++) t[n + i] = a[i];               // leaves
        for (int i = n - 1; i > 0; i--) t[i] = t[2 * i] + t[2 * i + 1];
    }

    void update(int i, int value) {                                // a[i] = value
        for (t[i += n] = value; i > 1; i >>= 1) t[i >> 1] = t[i] + t[i ^ 1];
    }

    int query(int l, int r) {                                      // sum of a[l..r)
        int res = 0;
        for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
            if ((l & 1) == 1) res += t[l++];
            if ((r & 1) == 1) res += t[--r];
        }
        return res;
    }
}

Lazy propagation

For range updates ("add 5 to every element in [l, r]") store pending updates at internal nodes and push them down only when a query or update needs to descend. Both range update and range query stay O(log n).

Fenwick tree (Binary Indexed Tree)

A cleverly indexed array where tree[i] stores the sum of a range ending at i whose length is the lowest set bit of i (i & -i). It is shorter to write and uses exactly n + 1 slots, but only works for invertible operations like sum.

class Fenwick {
    private final long[] tree;
    Fenwick(int n) { tree = new long[n + 1]; }          // 1-indexed

    void add(int i, long delta) {                       // a[i] += delta
        for (i++; i < tree.length; i += i & -i) tree[i] += delta;
    }
    long prefix(int i) {                                // sum of a[0..i]
        long s = 0;
        for (i++; i > 0; i -= i & -i) s += tree[i];
        return s;
    }
    long range(int l, int r) { return prefix(r) - (l > 0 ? prefix(l - 1) : 0); }
}
Key takeaways
  • Use prefix sums for static arrays; segment/Fenwick trees when values change.
  • Segment trees handle any associative operation (sum, min, max, gcd) and range updates via lazy propagation.
  • Fenwick trees are tiny and fast but limited to invertible operations like sums.
  • Both give O(log n) query and update.
Interview questions
QRange minimum queries on a static array — what's the fastest structure?hard

A sparse table: precompute minimums of every power-of-two-length range in O(n log n), then answer any query in O(1) using two overlapping ranges (min is idempotent). If updates are needed, use a segment tree.

QWhat does i & -i compute and why does Fenwick rely on it?medium

It isolates the lowest set bit of i (two's complement makes -i equal to ~i + 1). Fenwick index i is responsible for a range of exactly that length, so adding or removing the lowest bit moves to the next responsible index in O(log n) steps.