Segment Tree and Fenwick Tree (Binary Indexed Tree) in C++ and Python

Build a Fenwick tree and a segment tree in C++ and Python, and time them against a prefix array on a mixed workload of range sums and updates.

A row of sixteen square slots with one blue slot, four levels of dark brackets above it showing nested ranges with one bracket highlighted in blue, and a staircase of gray spans below it with three spans highlighted in green.

A range-sum structure answers “what is the sum from index l to index r” while the array keeps changing. This article compares three ways to do it. A prefix array answers in constant time but pays O(n) for every update. A Fenwick tree stores one span per index and answers and updates in O(log n). A segment tree stores a hierarchy of ranges and gives the same bounds with more flexibility. In a mixed workload of 10 percent updates and 90 percent range sums over 100,000 values, the prefix array took 22.976 ms, the Fenwick tree 0.441 ms and the segment tree 3.753 ms, all with the same checksum.

This guide covers the prefix-array update cost, the Fenwick low-bit walks, the segment tree’s partition and query, and the memory and constant-factor trade-offs, with a timed comparison on identical deterministic workloads in both languages. The Arrays article covers the contiguous layout both structures index, and the Binary Trees article covers the tree model behind the segment tree. The code was built and tested with GCC 13.3, Clang 18.1.3 and MSVC 19.44, and with Python 3.12. Both languages print byte-identical demo output.

What Are Segment and Fenwick Trees?

A Fenwick tree, or binary indexed tree, is an array in which slot i stores the sum of the span ending at i whose length is the lowest set bit of i, so a prefix sum walks down by that bit and an update walks up by it, both in O(log n). A segment tree is a binary tree whose nodes store the sums of nested ranges of the array, so a range query combines O(log n) node sums and a point update refreshes O(log n) ancestors.

Both structures solve the same problem: keep an array under point updates and range queries with logarithmic cost for both. A prefix array is faster on queries, O(1), and much slower on updates, O(n), because changing one element changes every prefix after it. The Fenwick tree is the smaller structure with the smaller constant when the operation can be undone, as addition can by subtraction. The segment tree is the general one: any associative operation works, including minimum and maximum, where a difference of prefixes means nothing.

The choice is a constant-factor and memory trade. A Fenwick tree over n values needs n + 1 integers and about log2 n additions per operation. A segment tree over a power-of-two layout needs 2 times the next power of two, which is at most 4n, and visits more nodes per query. In return it supports range updates through lazy propagation. Fenwick trees are common in counting and ranking problems, and segment trees in interval and computational-geometry problems that need more than addition.

Two range structures over the same eight values Above: segment tree nodes, each the sum of a range. Below: Fenwick slots, each a span ending at its index. Segment tree 1..8 sum 37 1..4 sum 24 5..8 sum 13 1..2: 8 3..4: 16 5..6: 10 7..8: 3 values 5 i=1 3 i=2 7 i=3 9 i=4 6 i=5 4 i=6 1 i=7 2 i=8 Fenwick tree slot 1: 5 slot 2: 8 slot 3: 7 slot 4: 24 slot 5: 6 slot 6: 10 slot 7: 1 slot 8: 37 The segment tree keeps 2 x 8 slots. The Fenwick tree keeps 8 + 1, and slot i spans i & -i values.
Figure 1: The same eight values under both structures. The segment tree stores the sums of nested ranges above the array, and the Fenwick tree stores one span ending at each index below it.

How This Was Measured

SettingValue
Date testedDecember 2, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC build
C++ toolchaing++ 13.3 and clang++ 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX /permissive-
Python runtimeCPython 3.12.3 under WSL2. CI covers Python 3.10 to 3.14
DataDeterministic values in 1..1000 from a documented xorshift64 generator
C++ workloadN = 100,000 values, M = 20,000 operations: 2,000 point updates and 18,000 inclusive range sums
Python workloadN = 10,000 values, M = 5,000 operations: 500 point updates and 4,500 range sums
What is timedThe build, then the whole mixed workload once per structure, with a monotonic clock
StatisticMilliseconds for one run, plus operations per second
CheckEvery query result is added to a checksum, and all three structures must produce the same value

The two languages use different sizes because the prefix array’s O(n) update makes a large Python run impractical. At N = 100,000, 2,000 updates already mean about 100 million additions. The article reports both scales and treats the ratios within each language as the result. The times are single runs on one machine and are indicative, while the checksums are exact.

Range Sums and the Cost of an Update

A prefix array stores prefix[i] = values[0] + ... + values[i]. A range sum is one subtraction, prefix[r] - prefix[l - 1], which is O(1) and as fast as a query can be. An update at index k must add the change to every prefix[i] with i >= k, which is O(n) writes. For a query-only workload nothing beats it. Once updates are even a few percent of the operations on a large array, those writes dominate.

The fix is to store partial sums instead of full prefixes, so that an update touches a few entries and a query combines a few. Both remaining structures do that with different partitions. The Fenwick tree’s partition is implicit in the index arithmetic, and the segment tree’s is explicit in the tree.

The Fenwick Tree: One Span per Index

In the one-based Fenwick array, slot i stores the sum of [i - lowbit(i) + 1, i], where lowbit(i) = i & -i is the lowest set bit of i. To add a value at index i, add it to slot i and walk i += lowbit(i) until the end of the array. To compute a prefix sum up to i, add slot i and walk i -= lowbit(i) until zero. Each step of the prefix walk clears a set bit, and each step of the update walk moves the lowest set bit higher, so neither walk takes more than about log2(n) + 1 steps.

The two Fenwick walks An update adds i & -i to move up. A prefix sum subtracts it to move down. Each visits at most log2(n) + 1 slots. update(5): 5 -> 6 -> 8 -> 16 1 1 2 2 3 1 4 4 5 1 6 2 7 1 8 8 9 1 10 2 11 1 12 4 13 1 14 2 15 1 16 16 Small numbers inside the slots are each index’s low bit. prefix(13): 13 -> 12 -> 8 -> 0 prefix(13) = slot 13 (13..13) + slot 12 (9..12) + slot 8 (1..8). update(5) changes every slot whose span contains index 5: 5..5, 5..6, 1..8 and 1..16. Slot 8 is on both paths: it holds 1..8, which covers index 5 and lies inside prefix(13).
Figure 2: The two Fenwick walks on 16 slots. update(5) adds the low bit and visits 5, 6, 8 and 16. prefix(13) subtracts it and visits 13, 12 and 8.

The representation is compact and cache-friendly: one array, no pointers, no recursion, and inner loops of a few instructions. In the C++ workload the Fenwick tree finished the 20,000 operations in 0.441 ms against 3.753 ms for the segment tree, 8.5 times faster, because each segment-tree query makes recursive calls and combines nodes while each Fenwick walk is a short loop.

The build is linear rather than n separate updates. The values are copied into slots 1..n, and then each slot is added once into its parent i + lowbit(i). When the pass reaches a slot, every child has already been folded into it, so one pass fills the whole tree.

A range that does not start at index 0 is a difference of two prefixes, sum(l..r) = prefix(r) - prefix(l - 1). That needs an operation that can be undone. Addition can, while minimum and maximum cannot, which is where the segment tree becomes necessary.

The Segment Tree: A Recursive Partition

A segment tree stores each range as a node. The root covers the whole array, each internal node splits its range into two halves, and each leaf holds one value. This implementation keeps the nodes in an array of 2 times the next power of two, with node k’s children at 2k and 2k + 1. A point update changes the leaf and climbs to the root, refreshing each ancestor, which is O(log n). A range query recurses from the root into only the children that overlap the query and adds the nodes that lie fully inside it, also O(log n).

The power-of-two layout pads the leaves up to the next power of two, so it uses at most 4n slots, the same bound textbooks give for the recursive layout over arbitrary n. Padding is the memory cost of the simple indexing.

The recursion depth is log2(n), so the call stack is never a problem, and the pitfalls below are about wrong sums rather than overflowing stacks. The recursive query mirrors the range partition and is the easiest to read. An iterative bottom-up query over the same array avoids the function calls and usually narrows the gap to the Fenwick tree, but this article measures the recursive form.

Choosing Between Them

Four questions settle the choice:

  • Can the operation be undone, as addition can by subtraction? Then the Fenwick tree gives the same bounds in less memory with a smaller constant.
  • Is the operation general, such as minimum, maximum, gcd or a matrix product? Then use the segment tree.
  • Are updates rare or absent? Then a prefix array is the fastest query structure.
  • Is memory tight? The Fenwick tree needs n + 1 integers against up to 4n for the segment tree.

Both structures answer in O(log n), so the difference is the constant and the flexibility. In the C++ workload the Fenwick tree was 8.5 times faster than the segment tree, and in Python 2.6 times. The cp-algorithms Fenwick tree page and segment tree page cover the variants, and the Wikipedia Fenwick tree article covers the history.

Segment Tree and Fenwick Tree Implementation in C++

The C++ header defines three classes with the same interface: a prefix array that rewrites its suffix on update, a Fenwick tree over a one-based vector, and a segment tree over a power-of-two leaf array with a recursive query. All sums are long long, so the checksums cannot overflow at these sizes.

class Fenwick {
public:
    // O(n) build: the values land in slots 1..n, then each slot is folded into
    // the slot that covers its range, which is slot i + (i & -i).
    void build(const std::vector<int>& values)
    {
        tree_.assign(values.size() + 1, 0);
        for (std::size_t i = 0; i < values.size(); ++i)
            tree_[i + 1] = values[i];
        for (std::size_t i = 1; i < tree_.size(); ++i) {
            const std::size_t parent = i + range_sum_detail::low_bit(i);
            if (parent < tree_.size())
                tree_[parent] += tree_[i];
        }
    }

    // values[index] += delta. The walk visits every node whose block covers
    // index, which is why the low bit i & -i is the whole trick.
    void add(std::size_t index, long long delta)
    {
        for (std::size_t i = index + 1; i < tree_.size(); i += range_sum_detail::low_bit(i))
            tree_[i] += delta;
    }

    // Inclusive range sum from two prefix sums.
    [[nodiscard]] long long sum(std::size_t left, std::size_t right) const
    {
        return prefix_sum(right + 1) - prefix_sum(left);
    }

    [[nodiscard]] long long total() const { return prefix_sum(tree_.size() - 1); }

    // Number of slots in the 1-indexed array, n + 1; slot 0 is unused. The
    // demo prints it to show the tree's memory shape.
    [[nodiscard]] std::size_t slots() const noexcept { return tree_.size(); }

private:
    // Sum of the first count values, 0 <= count <= n.
    [[nodiscard]] long long prefix_sum(std::size_t count) const
    {
        long long result = 0;
        for (std::size_t i = count; i > 0; i -= range_sum_detail::low_bit(i))
            result += tree_[i];
        return result;
    }

    std::vector<long long> tree_;   // 1-indexed; slot 0 is never used
};
class SegmentTree {
public:
    // Lays the values out in the leaves of the smallest complete binary tree
    // that covers them and folds the leaves upwards into the internal nodes.
    void build(const std::vector<int>& values)
    {
        leaf_count_ = 1;
        height_ = 0;
        while (leaf_count_ < values.size()) {
            leaf_count_ <<= 1;
            ++height_;
        }
        tree_.assign(2 * leaf_count_, 0);
        for (std::size_t i = 0; i < values.size(); ++i)
            tree_[leaf_count_ + i] = values[i];
        for (std::size_t node = leaf_count_ - 1; node > 0; --node)
            tree_[node] = tree_[2 * node] + tree_[2 * node + 1];
    }

    // values[index] += delta. Every ancestor of the leaf covers the index, so
    // each of them takes the delta too.
    void add(std::size_t index, long long delta)
    {
        for (std::size_t node = leaf_count_ + index; node > 0; node >>= 1)
            tree_[node] += delta;
    }

    // Inclusive range sum: the recursive partition over the leaf array.
    [[nodiscard]] long long sum(std::size_t left, std::size_t right) const
    {
        return query(1, 0, leaf_count_ - 1, left, right);
    }

    [[nodiscard]] long long total() const { return tree_[1]; }

    // Height in edges from the root down to a leaf: 0 for n = 1. The padded
    // leaves count, so the answer is ceil(log2(n)) for n > 1.
    [[nodiscard]] int height() const noexcept { return height_; }

    // Number of leaves including the padding to the next power of two.
    [[nodiscard]] std::size_t leaf_count() const noexcept { return leaf_count_; }

private:
    // Sum of the values in [left, right] that fall inside the node's inclusive
    // range [node_left, node_right]. A node that is fully inside the query
    // range answers from its stored sum; a node that is only partly inside is
    // split at mid, and the two halves are asked separately.
    [[nodiscard]] long long query(std::size_t node, std::size_t node_left,
                                  std::size_t node_right, std::size_t left,
                                  std::size_t right) const
    {
        if (right < node_left || node_right < left)
            return 0;
        if (left <= node_left && node_right <= right)
            return tree_[node];
        const std::size_t mid = node_left + (node_right - node_left) / 2;
        return query(2 * node, node_left, mid, left, right) +
               query(2 * node + 1, mid + 1, node_right, left, right);
    }

    std::vector<long long> tree_;
    std::size_t leaf_count_ = 0;
    int height_ = 0;
};

Output:

range sums: prefix array, Fenwick tree and segment tree
build 1..8 -> total 36
prefix sum 0..4 -> 15
update index 2 by +10 -> value 13
prefix sum 0..4 -> 25
Fenwick 0..4 -> 25, segment tree 0..4 -> 25
range sum 2..5 -> 28
after the update total -> 46, all three agree
segment tree height 3, Fenwick array 9 slots

Segment Tree and Fenwick Tree Implementation in Python

The Python module mirrors the C++ classes with the same method names and semantics. The Fenwick walks use the same low-bit arithmetic, and the segment tree keeps its sums in a list of 2 times the next power of two, with the same recursive query. Python integers do not overflow, so the two languages agree on every sum.

class Fenwick:
    """A Fenwick tree, or binary indexed tree, over a 1-indexed array.

    ``tree`` has n + 1 slots and slot 0 is unused.  Slot i covers the
    lowbit(i) = i & -i values that end at i: tree[4] covers values 0 to 3 and
    tree[6] covers values 4 and 5.  A prefix sum walks down from the end of the
    prefix by removing the low bit, an update walks up by adding it, and both
    walks visit O(log n) slots.
    """

    def __init__(self, values: Sequence[int]) -> None:
        self.build(values)

    def build(self, values: Sequence[int]) -> None:
        """Rebuild from values in O(n) by pushing each slot into its parent."""
        if len(values) < 1:
            raise ValueError("a range-sum structure needs at least one value")
        self.n = len(values)
        self.tree = [0] * (self.n + 1)
        for i, value in enumerate(values, start=1):
            self.tree[i] += value
            parent = i + (i & -i)
            if parent <= self.n:
                self.tree[parent] += self.tree[i]

    def add(self, index: int, delta: int) -> None:
        """Add delta to values[index], walking up the tree by the low bit."""
        _check_index(index, self.n)
        i = index + 1
        while i <= self.n:
            self.tree[i] += delta
            i += i & -i

    def sum(self, left: int, right: int) -> int:
        """Return values[left] + ... + values[right], both ends included."""
        _check_range(left, right, self.n)
        return self._prefix(right + 1) - self._prefix(left)

    def total(self) -> int:
        """Return the sum of the whole list."""
        return self._prefix(self.n)

    def _prefix(self, end: int) -> int:
        """Return the sum of the first end values, with end from 0 to n."""
        result = 0
        i = end
        while i > 0:
            result += self.tree[i]
            i -= i & -i
        return result
class SegmentTree:
    """A segment tree over a power-of-two leaf array.

    The leaves are padded to the next power of two, so the tree is complete and
    fits one flat list with the root at index 1: node k has children 2k and
    2k + 1, and the n values live in leaves to leaves + n - 1.  The padded
    leaves hold 0.  A range query walks the tree recursively and stops at any
    node whose whole span is inside the range.  The height is reported in
    edges: eight leaves give height 3 and a single leaf gives height 0.
    """

    def __init__(self, values: Sequence[int]) -> None:
        self.build(values)

    def build(self, values: Sequence[int]) -> None:
        """Fill the leaves with values and sum every internal node bottom up."""
        if len(values) < 1:
            raise ValueError("a range-sum structure needs at least one value")
        self.n = len(values)
        leaves = 1
        while leaves < self.n:
            leaves *= 2
        self.leaves = leaves
        self.tree = [0] * (2 * leaves)
        for i, value in enumerate(values):
            self.tree[leaves + i] = value
        for node in range(leaves - 1, 0, -1):
            self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1]

    def height(self) -> int:
        """Return the height in edges, 0 for a tree with one leaf."""
        return self.leaves.bit_length() - 1

    def add(self, index: int, delta: int) -> None:
        """Add delta to values[index], walking from its leaf to the root."""
        _check_index(index, self.n)
        node = self.leaves + index
        while node >= 1:
            self.tree[node] += delta
            node //= 2

    def sum(self, left: int, right: int) -> int:
        """Return values[left] + ... + values[right], both ends included."""
        _check_range(left, right, self.n)
        return self._query(1, 0, self.leaves - 1, left, right)

    def total(self) -> int:
        """Return the sum of the whole list, read from the root."""
        return self.tree[1]

    def _query(
        self,
        node: int,
        node_left: int,
        node_right: int,
        left: int,
        right: int,
    ) -> int:
        """Sum values[left..right] inside the span [node_left, node_right]."""
        if left <= node_left and node_right <= right:
            return self.tree[node]
        middle = (node_left + node_right) // 2
        result = 0
        if left <= middle:
            result += self._query(2 * node, node_left, middle, left, right)
        if right > middle:
            result += self._query(2 * node + 1, middle + 1, node_right, left, right)
        return result

The Python demo prints the same nine lines as the C++ program, byte for byte.

Measured: Mixed Workload

The workload builds a deterministic array, then runs the same fixed mix of updates and range sums once per structure, timing the build and the workload and adding every query result to a checksum.

std::vector<Operation> make_operations(std::uint64_t& state)
{
    std::vector<Operation> operations;
    operations.reserve(kOperations);
    for (std::size_t step = 0; step < kOperations; ++step) {
        Operation operation{false, 0, 0, 0, 0};
        if (step % kUpdateEvery == 0) {
            operation.update = true;
            operation.index = static_cast<std::size_t>(next_random(state) % kValues);
            operation.delta = static_cast<long long>(
                                  next_random(state) % static_cast<std::uint64_t>(kValueRange)) +
                              1;
        } else {
            const std::size_t a = static_cast<std::size_t>(next_random(state) % kValues);
            const std::size_t b = static_cast<std::size_t>(next_random(state) % kValues);
            operation.left = a < b ? a : b;
            operation.right = a < b ? b : a;
        }
        operations.push_back(operation);
    }
    return operations;
}
int main()
{
    // One generator state fills the values, then the operations: the workload
    // stream is identical for all three structures because it is generated once
    // and replayed.
    std::uint64_t state = kSeed;
    const std::vector<int> values = make_values(state);
    const std::vector<Operation> operations = make_operations(state);

    const std::size_t updates = (kOperations + kUpdateEvery - 1) / kUpdateEvery;
    const std::size_t queries = kOperations - updates;

    const Measurement prefix = measure<PrefixArray>("prefix rebuild", values, operations);
    const Measurement fenwick = measure<Fenwick>("Fenwick", values, operations);
    const Measurement segment = measure<SegmentTree>("segment tree", values, operations);

    std::cout << "mixed workload: N=" << kValues << " M=" << kOperations
              << " updates=" << updates << " queries=" << queries << '\n';
    print_header();
    print_row(prefix);
    print_row(fenwick);
    print_row(segment);

    bool ok = true;
    if (!(prefix.checksum == fenwick.checksum && fenwick.checksum == segment.checksum)) {
        std::cerr << "the three query checksums disagree: " << prefix.checksum << ", "
                  << fenwick.checksum << ", " << segment.checksum << '\n';
        ok = false;
    }

    // A fourth, plain array model checks the final total, so an update that all
    // three structures happened to miss would still be caught.
    std::vector<long long> model(values.begin(), values.end());
    for (const Operation& operation : operations) {
        if (operation.update)
            model[operation.index] += operation.delta;
    }
    long long model_total = 0;
    for (const long long value : model)
        model_total += value;
    if (prefix.total != model_total || fenwick.total != model_total ||
        segment.total != model_total) {
        std::cerr << "the final totals disagree with the plain array model: "
                  << prefix.total << ", " << fenwick.total << ", " << segment.total << " against "
                  << model_total << '\n';
        ok = false;
    }

    return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}

Output (C++):

mixed workload: N=100000 M=20000 updates=2000 queries=18000
structure        build_ms  workload_ms  ops_per_second  checksum
prefix rebuild   0.345     22.976       870477          303214309122
Fenwick          0.407     0.441        45351473        303214309122
segment tree     0.892     3.753        5329072         303214309122

Output (Python, smaller scale):

mixed workload: N=10000 M=5000 updates=500 queries=4500
structure        build_ms  workload_ms  ops_per_second  checksum
prefix rebuild   0.857     128.338      38959           7906140745
Fenwick          1.686     10.497       476308          7906140745
segment tree     2.226     27.602       181143          7906140745

In C++ the prefix array took 22.976 ms, the Fenwick tree 0.441 ms and the segment tree 3.753 ms for the same 20,000 operations and the same checksum, 303214309122. The Fenwick tree was 52 times faster than the prefix rebuild and 8.5 times faster than the segment tree. All three builds took under 1 ms, too little for a single run to rank them reliably.

In Python, with a tenth of the values and a quarter of the operations, the prefix rebuild took 128.338 ms, the Fenwick tree 10.497 ms and the segment tree 27.602 ms, with checksum 7906140745. The ordering is the same with much larger constants. The prefix array’s time grows with N times the number of updates, while the other two grow with the number of operations times log N.

Mixed workload: 10 percent updates, 90 percent range sums Workload time in milliseconds, linear scale per panel. All three structures return the same checksum. C++, N = 100,000, 20,000 operations prefix rebuild 22.976 ms Fenwick 0.441 ms segment tree 3.753 ms Python, N = 10,000, 5,000 operations prefix rebuild 128.338 ms Fenwick 10.497 ms segment tree 27.602 ms Fenwick was 52 times faster than the prefix rebuild in C++ and 12 times in Python. Single runs on one machine. The ratios are the result, not the milliseconds.
Figure 3: Mixed-workload time for the three structures, in C++ at 100,000 values and in Python at 10,000. The prefix array loses because every update rewrites its suffix.

Why the Prefix Array Loses

The prefix array’s cost is easy to underestimate because a query is one subtraction. Each update at index k rewrites every entry from k to the end, n – k additions. With U updates at random positions that is about U times n/2, against about U times log2(n) for the other two structures. At N = 100,000 and 2,000 updates it comes to about 100 million additions, which is where the 22.976 ms goes. The structure is still right for build-once, query-many workloads, and it is the baseline that shows what the other two pay for: the ability to change the array.

Five Ways a Range-Sum Structure Passes a Quick Test and Still Fails

Each program below runs cleanly and prints something plausible until the wrong number. The three C++ pitfalls are in the C++ repository and the two Python pitfalls in the Python repository, and the workflows rerun each one and check its wrong value beside the correct one.

1. A Low Bit That Is Not the Lowest Bit

void add_correct(std::vector<long long>& tree, std::size_t index, long long delta)
{
    for (std::size_t i = index + 1; i < tree.size(); i += low_bit(i))
        tree[i] += delta;
}

// Broken update walk: i += i & (i - 1). The increment clears the low bit, so the
// visited nodes are the wrong ones.
void add_broken(std::vector<long long>& tree, std::size_t index, long long delta)
{
    for (std::size_t i = index + 1; i < tree.size(); i += i & (i - 1))
        tree[i] += delta;
}
int main()
{
    std::cout << "fenwick_wrong_lowbit: i & (i - 1) clears the low bit instead of isolating it\n";

    std::vector<int> values(kCount);
    for (std::size_t i = 0; i < kCount; ++i)
        values[i] = static_cast<int>(i) + 1;

    // Build both trees with the correct walk, then copy one: the base data is
    // identical and only the two updates differ.
    std::vector<long long> base(kCount + 1, 0);
    for (std::size_t i = 0; i < kCount; ++i)
        add_correct(base, i, values[i]);
    std::vector<long long> correct = base;
    std::vector<long long> broken = base;

    add_correct(correct, 2, 10);
    add_correct(correct, 6, 10);
    add_broken(broken, 2, 10);
    add_broken(broken, 6, 10);

    std::cout << "correct sum 0..7 after updates at 2 and 6: "
              << range_sum(correct, 0, kCount - 1) << '\n';
    std::cout << "wrong lowbit sum 0..7 after updates at 2 and 6: "
              << range_sum(broken, 0, kCount - 1) << '\n';
    std::cout << "correct sum 0..3 after updates at 2 and 6: " << range_sum(correct, 0, 3) << '\n';
    std::cout << "wrong lowbit sum 0..3 after updates at 2 and 6: " << range_sum(broken, 0, 3) << '\n';
    std::cout << "violated invariant: the update walk must follow i + (i & -i)\n";

    return EXIT_SUCCESS;
}

Output:

fenwick_wrong_lowbit: i & (i - 1) clears the low bit instead of isolating it
correct sum 0..7 after updates at 2 and 6: 56
wrong lowbit sum 0..7 after updates at 2 and 6: 36
correct sum 0..3 after updates at 2 and 6: 20
wrong lowbit sum 0..3 after updates at 2 and 6: 10
violated invariant: the update walk must follow i + (i & -i)

The low bit is i & -i, the value of the lowest set bit. The expression i & (i - 1) clears that bit instead of isolating it, so the update walk steps to the wrong slots. After updates at indices 2 and 6 the correct sum 0..7 is 56 and the broken one is 36, and sum 0..3 is 20 against 10. The update walk must follow i + (i & -i).

2. A Segment Tree Child Range That Overlaps

long long query_wrong_child(const std::vector<long long>& tree, std::size_t node,
                            std::size_t node_left, std::size_t node_right, std::size_t left,
                            std::size_t right)
{
    if (right < node_left || node_right < left)
        return 0;
    if (left <= node_left && node_right <= right)
        return tree[node];
    if (2 * node >= tree.size())
        return tree[node];   // stops the broken walk from splitting below the leaves
    const std::size_t mid = node_left + (node_right - node_left) / 2;
    return query_wrong_child(tree, 2 * node, node_left, mid, left, right) +
           query_wrong_child(tree, 2 * node + 1, mid, node_right, left, right);
}
int main()
{
    std::cout << "segment_tree_wrong_child: the right-child query is passed [mid, right] "
                 "instead of [mid + 1, right]\n";

    const std::vector<long long> tree = build_tree();

    long long naive = 0;
    for (std::size_t index = 2; index <= 5; ++index)
        naive += static_cast<long long>(index) + 1;

    const long long correct = query_correct(tree, 1, 0, kCount - 1, 2, 5);
    const long long wrong = query_wrong_child(tree, 1, 0, kCount - 1, 2, 5);

    std::cout << "correct sum 2..5: " << correct << '\n';
    std::cout << "wrong right-child sum 2..5: " << wrong << '\n';
    std::cout << "the naive sum 2..5: " << naive << '\n';
    std::cout << "violated invariant: the right child range must start at mid + 1\n";

    return EXIT_SUCCESS;
}

Output:

segment_tree_wrong_child: the right-child query is passed [mid, right] instead of [mid + 1, right]
correct sum 2..5: 18
wrong right-child sum 2..5: 25
the naive sum 2..5: 18
violated invariant: the right child range must start at mid + 1

The right child is queried over [mid, right] instead of [mid + 1, right], so every right child is tested against bounds one slot to the left of the range it actually stores. A node that seems to fit inside the query reaches one slot past it, and the walk adds the value 7 at index 6. The range sum 2..5 comes out as 25 against the correct 18, which the naive loop confirms. The two child ranges must split the parent’s range without overlap.

3. An Update That Forgets the Suffix

void add_forgetting_suffix(std::vector<long long>& prefix, std::size_t index, long long delta)
{
    prefix[index] += delta;
}

// The correct update: prefix[index] changes and every later entry grows by the
// same delta, which is the suffix rebuild this article measures.
void add_rebuilding_suffix(std::vector<long long>& prefix, std::size_t index, long long delta)
{
    for (std::size_t i = index; i < prefix.size(); ++i)
        prefix[i] += delta;
}

long long range_sum(const std::vector<long long>& prefix, std::size_t left, std::size_t right)
{
    const long long before = left == 0 ? 0 : prefix[left - 1];
    return prefix[right] - before;
}

long long total(const std::vector<long long>& prefix)
{
    return prefix.back();
}
int main()
{
    std::cout << "prefix_update_forgets_suffix: the update changes prefix[index] only, "
                 "later entries stay stale\n";

    std::vector<long long> stale(kCount, 0);
    long long running = 0;
    for (std::size_t i = 0; i < kCount; ++i) {
        running += static_cast<long long>(i) + 1;
        stale[i] = running;
    }
    std::vector<long long> correct = stale;

    add_forgetting_suffix(stale, 2, 10);
    add_rebuilding_suffix(correct, 2, 10);

    std::cout << "stale sum 3..7: " << range_sum(stale, 3, 7) << '\n';
    std::cout << "correct sum 3..7 after the suffix rebuild: " << range_sum(correct, 3, 7)
              << '\n';
    std::cout << "stale total: " << total(stale) << '\n';
    std::cout << "correct total after the suffix rebuild: " << total(correct) << '\n';
    std::cout << "violated invariant: every prefix entry after the updated index must grow "
                 "by the delta\n";

    return EXIT_SUCCESS;
}

Output:

prefix_update_forgets_suffix: the update changes prefix[index] only, later entries stay stale
stale sum 3..7: 20
correct sum 3..7 after the suffix rebuild: 30
stale total: 36
correct total after the suffix rebuild: 46
violated invariant: every prefix entry after the updated index must grow by the delta

An update that changes only prefix[index] leaves every later prefix entry stale. The range 3..7 reads 20 against the correct 30, and the total reads 36 against 46 after the same update. Every prefix entry at or after the updated index must grow by the change, which is exactly the O(n) cost the prefix array pays.

4. A Prefix Walk in the Wrong Direction

def prefix_sum_wrong(tree: list[int], index: int) -> int:
    """Sum values[0..index] with the update walk, adding the low bit."""
    total = 0
    i = index + 1
    while i < len(tree):
        total += tree[i]
        i += i & -i
    return total


def main() -> None:
    fenwick = Fenwick(VALUES)
    correct = fenwick.sum(0, PREFIX_END)
    wrong = prefix_sum_wrong(fenwick.tree, PREFIX_END)
    print("fenwick_off_by_one: the prefix walk runs the wrong way")
    print(f"prefix sum 0..{PREFIX_END} -> wrong {wrong}, correct {correct}")

Output:

fenwick_off_by_one: the prefix walk runs the wrong way
prefix sum 0..4 -> wrong 52, correct 15

The prefix walk runs i += lowbit from the query index instead of subtracting, so it moves away from index zero and adds slots that cover later values. The prefix sum 0..4 comes out as 52 instead of 15. The update walk adds the low bit and the query walk subtracts it, and swapping them is the most common Fenwick bug.

5. A Segment Tree Query That Misses the Right Endpoint

class HalfOpenSegmentTree(SegmentTree):
    """A segment tree whose query treats right as exclusive."""

    def sum(self, left: int, right: int) -> int:
        """Return values[left] + ... + values[right - 1], missing the caller's right."""
        return self._query_half_open(1, 0, self.leaves - 1, left, right)

    def _query_half_open(
        self,
        node: int,
        node_left: int,
        node_right: int,
        left: int,
        right: int,
    ) -> int:
        """Sum the values in [left, right) that fall inside the node's span."""
        if right <= node_left or node_right < left:
            return 0
        if left <= node_left and node_right < right:
            return self.tree[node]
        middle = (node_left + node_right) // 2
        return self._query_half_open(
            2 * node, node_left, middle, left, right
        ) + self._query_half_open(2 * node + 1, middle + 1, node_right, left, right)


def main() -> None:
    tree = HalfOpenSegmentTree(VALUES)
    correct = SegmentTree(VALUES).sum(LEFT, RIGHT)
    wrong = tree.sum(LEFT, RIGHT)
    print("segment_tree_misses_right: a half-open query given inclusive bounds")
    print(f"range sum {LEFT}..{RIGHT} -> wrong {wrong}, correct {correct}")

Output:

segment_tree_misses_right: a half-open query given inclusive bounds
range sum 2..5 -> wrong 12, correct 18

The query treats the range as half-open and loops while left < right, but the caller passes inclusive bounds, so the right endpoint is never added. The range sum 2..5 returns 12 instead of 18. Convert inclusive bounds once at the entry point, or use one convention throughout.

Key Takeaways

  • A prefix array answers range sums in O(1) but pays O(n) per update. A Fenwick tree and a segment tree pay O(log n) for both.
  • The Fenwick tree stores one span per index, walks up by i & -i on updates and down by it on prefix sums, and needs only n + 1 integers.
  • The segment tree stores nested ranges, combines O(log n) nodes per query, and works for any associative operation, not just sums.
  • On 100,000 values in C++, the mixed workload took 22.976 ms with the prefix array, 0.441 ms with the Fenwick tree and 3.753 ms with the segment tree, with identical checksums.
  • At Python’s smaller scale the ordering held: 128.338, 10.497 and 27.602 ms.
  • Use the Fenwick tree for sums and other undoable operations, the segment tree for general operations, and the prefix array when updates are rare.

Frequently Asked Questions

Conclusion

The range-sum problem is a small decision with a large effect. A prefix array gives the fastest query and the slowest update. A Fenwick tree gives logarithmic updates and queries in one compact array. A segment tree gives the same bounds with a general combine function and a larger constant. On 100,000 values the measurements put numbers on the trade: 22.976 ms for the prefix array, 0.441 ms for the Fenwick tree and 3.753 ms for the recursive segment tree on the same checksummed workload, with the same ordering at Python’s scale.

The data structures hub places the range structures beside the other trees. Reach for the Fenwick tree when the operation can be undone and the array is large, the segment tree when the operation is general, and the prefix array for workloads that never update.

Source Code and Tests

The programs on this page are in the data-structures/segment-tree-fenwick-tree directory of two MYCPLUS example repositories:

LanguageRepository directoryBuild status
C++mycplus/cpp-examples: data-structures/segment-tree-fenwick-treeC++ segment tree and Fenwick tree build status
Pythonmycplus/python-examples: data-structures/segment-tree-fenwick-treePython segment tree and Fenwick tree build status

The C++ example builds and tests with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

The Python example runs with the standard library:

python3 -m unittest discover -s tests
python3 range_sum_demo.py
python3 workload_experiment.py

The demo’s output is compared byte for byte with tests/expected/ordered.txt. The tests compare all three structures with a naive array over random operations, cover single-element arrays, updates at both ends and full-range sums, and check that the three structures agree after every batch. The C++ workflow also runs the tests, demo, workload and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer and checks the workload’s checksums. Both workflows check each pitfall’s output. The timings are not checked, because they belong to one machine.

What I Verified

The example directories contain the test programs and the captured runs. The table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C++, g++ 13.3, C++17 and C++20Pass (6 of 6 tests)Not applicable
Build and tests, C++, clang++ 18.1.3, C++17 and C++20Pass (6 of 6 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (6 of 6 tests, C++17 and C++20)
AddressSanitizer and UndefinedBehaviorSanitizer, C++ tests, demo and pitfallsPass (6 of 6 tests)Not applicable
Python tests and demo, CPython 3.12Pass (26 tests, demo byte-identical to C++)Not applicable
Five pitfalls, each printing its documented wrong valuePass (3 C++ and 2 Python)Not applicable
Workload experiment, C++ and PythonRun, output aboveNot run
Independent rerun on a second Linux x86-64 machine (GCC 13.3, Clang 18.1.3, Python 3.13)Pass (C++ 6 of 6 with both compilers, Python tests pass, demos and pitfalls byte-identical, workload checksums identical with the same ordering: Fenwick 39 times and 11 times faster than the prefix rebuild)Not applicable

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, PyPy, range updates, operations other than addition, and timings on other machines beyond the rerun above.

Scroll to Top