Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Segment Trees & Fenwick Trees

Range queries and updates in O(log n).

An array of a million sensor readings keeps changing, and you must answer "what is the sum, or the minimum, of readings ll through rr?" thousands of times a second. Rescanning costs up to a million steps per question; a prefix-sum array answers in one step but must be rebuilt after every change. A segment tree does both in a few dozen steps, and a Fenwick tree does sums with two three-line loops.

What you’ll learn

  • Compare naive scans, prefix sums, square-root decomposition and trees for range queries with updates, and pick the lightest one that fits.
  • Build a segment tree for any associative operation, answer range queries and point updates in O(log⁡n)O(\log n), and prove that a query visits at most four nodes per level.
  • Implement the iterative bottom-up segment tree, and descend a segment tree to find the first index with a property in O(log⁡n)O(\log n).
  • Implement a Fenwick tree with lowest-set-bit jumps for prefix sums and point updates, and turn it into range updates with point queries.
  • Recognize range-query problems, including inversion counting and "smaller elements to the right" with a Fenwick tree over compressed values.

Range queries meet updates

The problem: an array a[0..n−1]a[0..n-1] and a stream of two kinds of operations, mixed in any order:

  • update: set a[i]=xa[i] = x;
  • range query: report the sum (or minimum, maximum, gcd, …) of a[l..r]a[l..r], inclusive.

Each classic structure makes one of the two cheap:

ApproachupdatequeryIdea
Scan the rangeO(1)O(1)O(n)O(n)store nothing
Prefix sumsO(n)O(n)O(1)O(1)P[r+1]−P[l]P[r+1] - P[l]; an update shifts every later prefix
Square-root decompositionO(1)O(1)O(n)O(\sqrt n)blocks of about n\sqrt n elements, each with its stored sum
Segment treeO(log⁡n)O(\log n)O(log⁡n)O(\log n)stored answers for halves, quarters, eighths, …
Fenwick treeO(log⁡n)O(\log n)O(log⁡n)O(\log n)stored sums of ranges whose lengths are powers of two; sums only
Worst-case costs for range sums. Over qq operations the first three cost up to O(qn)O(qn), O(qn)O(qn) and O(qn)O(q\sqrt n), the trees O(qlog⁡n)O(q\log n).

Square-root decomposition is the natural middle ground. Cut the array into blocks of bb elements and store each block's sum. A query adds the at most 2(b−1)2(b-1) elements in the two partial end blocks and at most n/bn/b whole block sums; an update changes one element and one block sum. The query cost O(b+n/b)O(b + n/b) is smallest at b=nb = \sqrt n. It is simple and flexible, and the Optimal lesson Sparse Tables & Square-Root Decomposition develops it; for plain range queries with updates, trees do better.

Check your understanding

An array of 10510^5 numbers never changes, and you must answer 10510^5 range-sum queries. Which structure is both the simplest and the fastest here?

  1. A segment tree
  2. A Fenwick tree
  3. A prefix-sum array
  4. Square-root decomposition
Show the answer

C. A prefix-sum array

Without updates, one O(n)O(n) pass computes PP, and each query is P[r+1]−P[l]P[r+1] - P[l] in O(1)O(1): O(n+q)O(n + q) in total. Trees pay O(log⁡n)O(\log n) per query for the ability to absorb updates, which this problem never uses.

The segment tree

python
class SegTree:                                    # range sums; any associative op works
    def __init__(self, a):
        self.n = len(a)
        self.t = [0] * (4 * self.n)               # node 1 = root; children 2v and 2v + 1
        self._build(a, 1, 0, self.n - 1)

    def _build(self, a, v, l, r):                 # O(n): each node once
        if l == r:
            self.t[v] = a[l]; return
        m = (l + r) // 2
        self._build(a, 2 * v, l, m); self._build(a, 2 * v + 1, m + 1, r)
        self.t[v] = self.t[2 * v] + self.t[2 * v + 1]

    def query(self, ql, qr, v=1, l=0, r=None):    # sum of a[ql..qr], inclusive: O(log n)
        if r is None: r = self.n - 1
        if qr < l or r < ql:
            return 0                              # disjoint: skip, return the identity
        if ql <= l and r <= qr:
            return self.t[v]                      # inside: take the whole node
        m = (l + r) // 2                          # partial overlap: split
        return self.query(ql, qr, 2 * v, l, m) + self.query(ql, qr, 2 * v + 1, m + 1, r)

    def update(self, i, x, v=1, l=0, r=None):     # a[i] = x: O(log n), one root-leaf path
        if r is None: r = self.n - 1
        if l == r:
            self.t[v] = x; return
        m = (l + r) // 2
        if i <= m: self.update(i, x, 2 * v, l, m)
        else:      self.update(i, x, 2 * v + 1, m + 1, r)
        self.t[v] = self.t[2 * v] + self.t[2 * v + 1]

The textbook recursive version. A query meets three cases at every node: disjoint (skip it), inside (take its stored value), partial (split into both children). An update walks to one leaf and recomputes every node on the way back up.

Check your understanding

On the array [4,9,2,7,5,1,8,3][4, 9, 2, 7, 5, 1, 8, 3], which nodes does the query for the sum of a[2..7]a[2..7] take whole?

  1. Node 5, covering [2,3][2, 3], and node 3, covering [4,7][4, 7]: 9+17=269 + 17 = 26
  2. Nodes 5, 6 and 7, covering [2,3][2, 3], [4,5][4, 5] and [6,7][6, 7]
  3. The six leaves from a[2]a[2] to a[7]a[7]
  4. The root, minus node 4, covering [0,1][0, 1]
Show the answer

A. Node 5, covering [2,3][2, 3], and node 3, covering [4,7][4, 7]: 9+17=269 + 17 = 26

The root splits; node 2 [0,3][0, 3] splits; node 4 [0,1][0, 1] is disjoint and skipped; node 5 [2,3][2, 3] is inside and taken; node 3 [4,7][4, 7] is inside and taken. So [2,7]=[2,3]∪[4,7][2, 7] = [2, 3] \cup [4, 7], and the answer is 9+17=269 + 17 = 26. A query always takes the largest nodes that fit.

Why every query costs O(log n)

DerivationProof
  1. #{split nodes on a level} ≤ 2\#\{\text{split nodes on a level}\}\ \le\ 2

    The nodes of one level cover disjoint intervals in left-to-right order. A node is split only when it partly overlaps [l,r][l, r], so it contains one element inside the range and one outside: it straddles the left boundary (contains l−1l - 1 and ll) or the right one (contains rr and r+1r + 1). At most one node per level straddles each boundary:

  2. #{visited on level d+1} ≤ 2⋅#{split on level d} ≤ 4\#\{\text{visited on level } d+1\}\ \le\ 2\cdot\#\{\text{split on level } d\}\ \le\ 4

    Every visited node except the root is a child of a split node, so the visits on one level are at most twice the splits on the level above:

  3. Tquery(n)=O(log⁡n),Tupdate(n)=⌈log⁡2n⌉+1 nodesT_{\text{query}}(n) = O(\log n), \qquad T_{\text{update}}(n) = \lceil\log_2 n\rceil + 1 \text{ nodes}

    Summing over the levels bounds the work. For nn a power of two the exact maximum is 4log⁡2n−14\log_2 n - 1 visited nodes: 11 for n=8n = 8, as the widget's range [1,6][1, 6] shows.

Predict before you look

An array has n=16n = 16 elements. At most how many segment-tree nodes can one range query visit, counting the skipped ones?

Show the answer

15 nodes

4log⁡216−1=154\log_2 16 - 1 = 15 of the 31 nodes: the root, then up to 4 nodes on each of the 4 levels below it, except that the second level has only 2 nodes. A query over a range like [1,14][1, 14] meets both boundaries on every level down to the leaves.

Any associative operation. Nothing in the proof uses addition. Each node needs an associative operation with an identity element, a monoid: sum (0), minimum (+∞+\infty), maximum (−∞-\infty), gcd (0), xor (0), or a pair such as "maximum and how often it occurs". Commutativity is not needed, provided results are always combined left before right; matrix products, which compose functions along the array, work too.

The iterative version. In contests, the bottom-up tree below is shorter and faster: the leaves live at t[n..2n−1]t[n..2n-1], node ii has children 2i2i and 2i+12i+1, and a query climbs from both ends of a half-open range [l,r)[l, r) toward the root. It works for every nn, not only powers of two.

cpp
#include <vector>
using namespace std;

struct SegTree {                         // range sums; swap op and ID for min, max, gcd, ...
    int n;
    vector<long long> t;                 // leaves at t[n .. 2n-1]; node i has children 2i, 2i+1
    static long long op(long long a, long long b) { return a + b; }
    static constexpr long long ID = 0;   // identity of op
    explicit SegTree(const vector<long long>& a) : n((int)a.size()), t(2 * a.size(), ID) {
        for (int i = 0; i < n; ++i) t[n + i] = a[i];
        for (int i = n - 1; i >= 1; --i) t[i] = op(t[2 * i], t[2 * i + 1]);    // O(n)
    }
    void set(int i, long long x) {       // a[i] = x: O(log n)
        for (t[i += n] = x; i > 1; i >>= 1) t[i >> 1] = op(t[i & ~1], t[i | 1]);
    }
    long long query(int l, int r) const {   // op over a[l .. r-1], half-open: O(log n)
        long long resl = ID, resr = ID;      // two sides keep left-to-right order
        for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
            if (l & 1) resl = op(resl, t[l++]);
            if (r & 1) resr = op(t[--r], resr);
        }
        return op(resl, resr);
    }
};

Half the memory of the recursive layout and no recursion. On each level the query takes the node at the left end if it is a right child, and the node just before the right end if that one is a left child, then moves both ends up a level. The two accumulators make it correct even for non-commutative operations.

Descending the tree. Many questions ask for a position, not a value: the first index i≥li \ge l with a[i]≥xa[i] \ge x, or the first prefix whose sum reaches kk. Walk down, entering a subtree only if its stored value says the answer can be inside. Each level costs O(1)O(1) beyond the nodes an ordinary query would visit, so the search is O(log⁡n)O(\log n), against O(log⁡2n)O(\log^2 n) for a binary search that calls query at every step.

python
def first_at_least(t, ql, x, v, l, r):   # t: a max-tree in the recursive layout
    """Smallest i >= ql with a[i] >= x in node v's range [l, r], or -1. O(log n)."""
    if r < ql or t[v] < x:
        return -1                         # nothing usable here: prune the subtree
    if l == r:
        return l
    m = (l + r) // 2
    i = first_at_least(t, ql, x, 2 * v, l, m)
    return i if i != -1 else first_at_least(t, ql, x, 2 * v + 1, m + 1, r)

Call it as first_at_least(t, ql, x, 1, 0, n - 1). Typical uses: the first seat row with at least xx free seats, or the first bin that can still hold an item.

Fenwick trees

  • Prefix sum a[1]+⋯+a[p]a[1] + \cdots + a[p]: add F[p]F[p], then clear the lowest set bit of pp and repeat until p=0p = 0. For example prefix(7)=F[7]+F[6]+F[4]\mathrm{prefix}(7) = F[7] + F[6] + F[4], since 7=1112→1102→1002→07 = 111_2 \to 110_2 \to 100_2 \to 0: one read per 1-bit of pp.
  • Point update a[p]+=δa[p] \mathrel{+}= \delta: add δ\delta to F[p]F[p], then add the lowest set bit to pp and repeat while p≤np \le n; this visits exactly the entries whose ranges contain pp.
  • Range sum of positions l..rl..r: prefix(r)−prefix(l−1)\mathrm{prefix}(r) - \mathrm{prefix}(l-1).

Both loops run at most ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1 times. The Optimal lesson Fenwick Trees in Depth proves why the ranges fit together.

python
class Fenwick:                       # 1-indexed: f[p] = a[p - lowbit(p) + 1] + ... + a[p]
    def __init__(self, n):
        self.n, self.f = n, [0] * (n + 1)

    def add(self, p, delta):         # a[p] += delta: O(log n)
        while p <= self.n:
            self.f[p] += delta
            p += p & -p              # next range that contains position p

    def prefix(self, p):             # a[1] + ... + a[p]: O(log n)
        s = 0
        while p > 0:
            s += self.f[p]
            p -= p & -p              # drop the lowest set bit
        return s

    def range_sum(self, l, r):       # a[l] + ... + a[r], inclusive, 1-indexed
        return self.prefix(r) - self.prefix(l - 1)

n+1n + 1 entries instead of 2n2n or 4n4n, two three-line loops, and fast in practice. To set a[p]=xa[p] = x, keep a copy of the array and add δ=x−a[p]\delta = x - a[p].

Range answers come from subtracting two prefixes, so a Fenwick tree needs an invertible operation: sums, xor, counts. Range minimum or maximum needs a segment tree, or a sparse table if the array never changes.

Range update, point query. Store the difference array instead: adding vv to positions l..rl..r becomes add(l, v) and add(r + 1, -v), and the current value at position pp is prefix(p). Range updates with range sums need a second Fenwick tree, derived in Fenwick Trees in Depth, or a segment tree with lazy propagation.

Check your understanding

Which positions does the Fenwick entry F[12]F[12] cover?

  1. Only position 12
  2. Positions 9 to 12
  3. Positions 1 to 12
  4. Positions 5 to 12
Show the answer

B. Positions 9 to 12

12=1100212 = 1100_2, so lowbit(12)=4\mathrm{lowbit}(12) = 4, and F[12]F[12] covers (12−4,12]={9,10,11,12}(12 - 4, 12] = \{9, 10, 11, 12\}. Entries with odd indices cover one position, multiples of 4 that are not multiples of 8 cover four, and so on.

Recognizing it

Reach for a segment tree or a Fenwick tree when:

  • range questions (sum, minimum, maximum, gcd, count) are interleaved with updates, and nn and qq are around 10510^5 to 10610^6, so that O(log⁡n)O(\log n) per operation fits and O(n)O(n) does not;
  • a scan asks "how many earlier (or later) elements are smaller, larger, or inside a value range": keep a Fenwick tree over the values, after coordinate compression if they are large;
  • offline points and queries can be sorted by one coordinate while a Fenwick tree counts along the other;
  • a query asks for a position: the first index with a property, or the kk-th smallest stored value.
Problem (in brief)Key ideaCost
Point updates and range sumsFenwick treeO(log⁡n)O(\log n) per operation
Point updates and range minimumSegment tree with min⁡\min and identity +∞+\inftyO(log⁡n)O(\log n) per operation
Count the inversions, or for each element the smaller elements to its rightScan, querying and inserting ranks in a Fenwick tree over compressed valuesO(nlog⁡n)O(n\log n)
The first index i≥li \ge l with a[i]≥xa[i] \ge x, under updatesMax segment tree, then descendO(log⁡n)O(\log n) per operation
Add vv to a[l..r]a[l..r] many times, reading single elements in betweenFenwick tree over the difference arrayO(log⁡n)O(\log n) per operation
Five classic shapes. Range additions with range sums or minimums call for lazy propagation, the subject of an Optimal lesson.
python
def count_inversions(a):              # pairs i < j with a[i] > a[j]: O(n log n)
    rank = {v: k + 1 for k, v in enumerate(sorted(set(a)))}   # coordinate compression
    fw, inv = Fenwick(len(rank)), 0
    for i, x in enumerate(a):         # fw counts the values seen so far
        inv += i - fw.prefix(rank[x]) # earlier values strictly greater than x
        fw.add(rank[x], 1)
    return inv

For [3,1,2,5,4][3, 1, 2, 5, 4] it returns 3: the pairs (3,1)(3, 1), (3,2)(3, 2) and (5,4)(5, 4). Scanning from the right and counting smaller values instead answers "how many smaller elements lie to the right of each element".

Check your understanding

An array of 2⋅1052\cdot10^5 integers receives 2⋅1052\cdot10^5 operations in any order: "set a[i]=xa[i] = x" and "report the minimum of a[l..r]a[l..r]". Which structure fits?

  1. A Fenwick tree
  2. A sparse table
  3. A prefix-minimum array
  4. A segment tree storing minimums
Show the answer

D. A segment tree storing minimums

Minimum is associative with identity +∞+\infty, so a segment tree answers each query and update in O(log⁡n)O(\log n). With depth ⌈log⁡2(2⋅105)⌉=18\lceil\log_2(2\cdot10^5)\rceil = 18, a query visits at most about 70 nodes, so all the operations together take roughly 1.4⋅1071.4\cdot10^7 node visits, far within limits.

Key takeaways

  • Prefix sums answer static range sums in O(1)O(1) but pay O(n)O(n) per update; square-root decomposition balances both at O(n)O(\sqrt n); segment and Fenwick trees make both O(log⁡n)O(\log n).
  • A segment tree stores the operation's result for halves, quarters, … of the array. A query splits at most 2 and visits at most 4 nodes per level, so queries and point updates cost O(log⁡n)O(\log n) for any associative operation with an identity.
  • The iterative tree keeps the leaves at t[n..2n−1]t[n..2n-1] and works for every nn; descending a tree of maximums finds the first index with a[i]≥xa[i] \ge x in O(log⁡n)O(\log n).
  • A Fenwick tree stores the sums of the ranges (p−lowbit(p),p](p - \mathrm{lowbit}(p), p]: prefix queries clear the lowest set bit, updates add it. It uses n+1n + 1 entries and a few lines of code, but only for invertible operations such as sums.
  • Signals: many range queries mixed with updates; counts of earlier or later smaller elements, over compressed values; range additions with point reads, through a Fenwick tree over differences.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does a segment-tree range query split at most two nodes on each level?

  1. Because the tree is balanced
  2. Because a split node only partly overlaps [l,r][l, r], so it straddles one of the range's two boundaries, and the nodes of one level are disjoint
  3. Because each node has exactly two children
  4. Because a query stops as soon as it reaches a leaf
Show the answer

B. Because a split node only partly overlaps [l,r][l, r], so it straddles one of the range's two boundaries, and the nodes of one level are disjoint

A node that partly overlaps [l,r][l, r] contains an element inside the range and one outside, so it contains l−1l - 1 and ll, or rr and r+1r + 1. The nodes of one level cover disjoint intervals, so at most one contains each boundary: at most 2 split nodes, and at most 4 visited nodes, per level.

Question 2

In a Fenwick tree, which entries does prefix(13) add up?

  1. F[13]+F[14]+F[16]F[13] + F[14] + F[16]
  2. F[1]+F[2]+⋯+F[13]F[1] + F[2] + \cdots + F[13]
  3. F[13]+F[12]+F[8]F[13] + F[12] + F[8]
  4. F[13]+F[11]+F[7]F[13] + F[11] + F[7]
Show the answer

C. F[13]+F[12]+F[8]F[13] + F[12] + F[8]

13=1101213 = 1101_2; dropping the lowest set bit repeatedly gives 11002=121100_2 = 12, then 10002=81000_2 = 8, then 0. The ranges (12,13](12, 13], (8,12](8, 12] and (0,8](0, 8] partition (0,13](0, 13]: three reads, one per 1-bit of 13.

Question 3

Why can't a plain Fenwick tree answer the minimum of an arbitrary range a[l..r]a[l..r]?

  1. It answers a range by subtracting two prefix results, and minimum has no inverse
  2. Its entries are too small to hold minimums
  3. It is 1-indexed
  4. Minimum is not associative
Show the answer

A. It answers a range by subtracting two prefix results, and minimum has no inverse

sum(l..r)=prefix(r)−prefix(l−1)\mathrm{sum}(l..r) = \mathrm{prefix}(r) - \mathrm{prefix}(l-1) works because addition can be undone. Knowing min⁡(a[1..r])\min(a[1..r]) and min⁡(a[1..l−1])\min(a[1..l-1]) does not determine min⁡(a[l..r])\min(a[l..r]). Use a segment tree, or a sparse table if the array never changes.

Question 4

To count inversions, you scan aa from left to right with a Fenwick tree over the compressed values and, before inserting a[i]a[i], add i−prefix(rank(a[i]))i - \mathrm{prefix}(\mathrm{rank}(a[i])). What does that term count?

  1. The earlier elements smaller than or equal to a[i]a[i]
  2. The later elements smaller than a[i]a[i]
  3. The elements equal to a[i]a[i]
  4. The earlier elements strictly greater than a[i]a[i]
Show the answer

D. The earlier elements strictly greater than a[i]a[i]

After ii insertions the tree counts a[0..i−1]a[0..i-1] by value, and prefix(rank(a[i]))\mathrm{prefix}(\mathrm{rank}(a[i])) counts those ≤a[i]\le a[i]. The other i−prefix(⋅)i - \mathrm{prefix}(\cdot) are greater: each forms an inversion with a[i]a[i]. Summing over ii counts every inversion once, in O(nlog⁡n)O(n\log n).

Go deeper

Further reading

  • P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.
  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapters 9 and 28.
  • CP-Algorithms, Segment Tree and Fenwick Tree.
  • S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020), book 1, chapter 2.