Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Advanced & Niche/Segment Tree / Fenwick (BIT)

Learn the pattern · ~15 min

Segment Tree / Fenwick (BIT)

also called Fenwick tree, binary indexed tree, range query point update

Store the answer for ranges that double in size, so any query is a handful of stored blocks and any update fixes only the blocks above one leaf.

Signalsrange queries mixed with updatescount elements smaller/greater than x seen so farinversionsLearn firstPrefix Sum
Cheat sheet and practice

Reach for it when you read

  • +Range questions (sum, min, max, gcd of a[l..r]) mixed with point updates, both up to about 10⁵.
  • +"How many earlier elements are smaller / larger than this one?": index a tree by value and count as you go.
  • +Find the first position whose value is ≥ x, or the k-th element still alive, while values change.
  • +Add v to a whole range and still answer range questions: lazy propagation.
  • +A DP whose transition is "best over all values below x" (LIS-style), too slow as a loop.

Not this one when

  • ×No updates at all: prefix sums (or a sparse table for min/max) answer in O(1).
  • ×All updates come first, then all questions: a difference array, then prefix sums.
  • ×Only the max or min of a sliding window of fixed size: a monotonic deque.

Learn Segment Tree / Fenwick (BIT)

First, what is a "segment"?

A segment of an array is a range without gaps: a[2..5] means a[2], a[3], a[4], a[5]. A segment tree stores the sum (or min, or max) of many segments at once: the whole array, its two halves, their halves, and so on down to single elements. Any segment you're asked about can then be glued together from a few of those stored blocks.

How is the tree built?

Take a = [5, 8, 6, 3, 2, 7, 2, 6], n = 8. We keep the tree in one array t of size 2n:

The leaves t[8..15] hold the array itself. Every other node i holds the sum of its two children, t[2i] + t[2i + 1]. Node 1 is the root.

Build from the bottom, i = 7 down to 1, so both children are ready when you reach a parent:

node i children what happens t[i]
7 14, 15 a[6] + a[7] = 2 + 6 8
6 12, 13 a[4] + a[5] = 2 + 7 9
5 10, 11 a[2] + a[3] = 6 + 3 9
4 8, 9 a[0] + a[1] = 5 + 8 13
3 6, 7 right half: 9 + 8 17
2 4, 5 left half: 13 + 9 22
1 2, 3 the whole array: 22 + 17 39

Drawn as a tree, each node is index:sum [range]:

Text
                              1:39 [0..7]
            2:22 [0..3]                         3:17 [4..7]
   4:13 [0..1]       5:9 [2..3]        6:9 [4..5]        7:8 [6..7]
   8:5      9:8     10:6     11:3     12:2     13:7     14:2     15:6

Each level covers the whole array once, in blocks that halve as you go down. There are log₂ 8 + 1 = 4 levels.

The code for it

C++
int n;
vector<long long> t;                        // t[1] is the root, leaves are t[n..2n-1]
void build(const vector<long long>& a) {
    n = a.size();
    t.assign(2 * n, 0);
    for (int i = 0; i < n; i++) t[n + i] = a[i];               // the leaves
    for (int i = n - 1; i > 0; i--) t[i] = t[2 * i] + t[2 * i + 1];   // parent = left + right
}

You don't need to memorise this. It's the table above: copy the array into the second half of t, then fill each parent from its two children, right to left.

Why 2i and 2i + 1? Because then we need no pointers at all: the children of node i are at 2i and 2i + 1, and the parent of node i is at i / 2. Moving up the tree is just halving an index. (n doesn't have to be a power of two. The picture gets messier, but the same code works.)

Fine, but how does this help us?

Here's the classic problem: range sums with corrections. You get a mix of two kinds of requests: "what's the sum of a[l..r]?" and "set a[i] = v". For example:

request how you find it by hand answer
sum of a[1..5] 8 + 6 + 3 + 2 + 7 26
set a[3] = 10 the array is now [5, 8, 6, 10, 2, 7, 2, 6]
sum of a[1..5] 8 + 6 + 10 + 2 + 7 33

The brute force

Add the range up every time:

C++
long long bruteSum(const vector<long long>& a, int l, int r) {
    long long s = 0;
    for (int i = l; i <= r; i++) s += a[i];   // up to n steps per question
    return s;
}

A correction is O(1), but every question costs up to n steps. With 10⁵ questions on n = 10⁵, that's 10¹⁰ steps. Time limit exceeded.

Prefix sums flip the problem: questions become O(1), but a correction at index 0 changes every prefix, up to n rewrites. The same 10¹⁰ for 10⁵ corrections. You need something in between.

The one thought that fixes it

Stop at the first question, a[1..5]. Look at the tree. You don't need five leaves: the range is the leaf 9:8 (a[1]), plus the block 5:9 (a[2..3]), plus the block 6:9 (a[4..5]). Three numbers: 8 + 9 + 9 = 26.

Now the correction a[3] = 10. Which stored sums contain a[3]? Only the ones on its path to the root: 11, 5, 2, 1. One node per level, four nodes. Everything else is still right.

That's the trade we wanted:

  • A correction touches one block per level: log₂ n + 1 nodes.
  • A question needs at most two blocks per level. Inside a level you never need three neighbouring blocks, because two neighbours with the same parent can be replaced by that parent one level up.

The query finds those blocks from the bottom. Put l and r on the leaves as a half-open range [l, r) and climb both. If l is odd, it's a right child: its parent would stick out to the left of the range, so take t[l] itself and step right. If r is odd, r − 1 is a left child whose parent sticks out to the right: take t[r − 1].

The code for the problem

C++
void update(int i, long long v) {
    i += n;
    t[i] = v;
    while (i > 1) { i /= 2; t[i] = t[2 * i] + t[2 * i + 1]; }   // repair each ancestor
}
long long query(int l, int r) {             // sum of a[l..r], inclusive
    long long res = 0;
    for (l += n, r += n + 1; l < r; l /= 2, r /= 2) {
        if (l & 1) res += t[l++];           // l is a right child: take it, step right
        if (r & 1) res += t[--r];           // r - 1 is a left child: take it
    }
    return res;
}

Dry run

The question a[1..5] becomes leaves [9, 14).

l r what happens res
9 14 l is odd: take t[9] = 8 (a[1]), l becomes 10. r is even 8
5 7 l is odd: take t[5] = 9 (a[2..3]). r is odd: take t[6] = 9 (a[4..5]) 26
3 3 l = r, nothing left 26

Now update(3, 10): the leaf is 3 + 8 = 11.

node what happens new value
11 the leaf a[3] 10
5 6 + 10 16
2 13 + 16 29
1 29 + 17 46

The same query again takes t[9] = 8, t[5] = 16, t[6] = 9: 33, the same answers as the brute force.

Why it's O(log n)

Count nodes, not loop lines. The tree has log₂ n + 1 levels. An update repairs exactly one node per level. A query climbs once and takes at most two nodes per level. So both are O(log n); for n = 10⁵ that's about 17 levels. Building is O(n): each of the n − 1 parents is one addition. Space: 2n numbers.

10⁵ questions and corrections now cost about 3.4 × 10⁶ steps instead of 10¹⁰, by storing sums of halving blocks.

Range minimum? Change the merge

Replace + with min everywhere, and start res at LLONG_MAX (a value that leaves min unchanged):

C++
t[i] = min(t[2 * i], t[2 * i + 1]);

On the same array, the minimum of a[1..5] is 2 and of a[0..3] is 3. Max, gcd and xor work the same way. The merge must be associative, and the start value must not change the answer.

Count smaller values seen so far? Index by value

Make the leaves stand for values, not positions. Walk the array right to left; for each x, ask for the sum of leaves 0..x − 1 (how many smaller values are to its right), then add 1 at leaf x. For [5, 2, 6, 1] that gives [2, 1, 1, 0]. Big values? Compress them to their rank first.

Add v to a whole range?

Then a correction touches many leaves. The fix is a lazy tag on each node ("everything below me gets +v, not yet applied"), pushed down only when a query passes through. If you only ever read single elements, a Fenwick tree on the difference array is shorter.

Remember this

  • Point updates mixed with range questions → segment tree. No updates at all → prefix sums are enough.
  • Leaves at t[n..2n − 1], children of i at 2i and 2i + 1, build from n − 1 down to 1.
  • The query is half-open: r += n + 1 for an inclusive r. An off-by-one here silently drops the last element.
  • The merge must be associative (sum, min, max, gcd), and the empty value must leave it unchanged.

Practise it on Range Sum Query - Mutable, then Dynamic Range Sum Queries, Dynamic Range Minimum Queries (merge = min), Count of Smaller Numbers After Self (index by value), Hotel Queries (walk down to the first big enough) and Reverse Pairs.

Watch it work, line by line

Range Sum Query - Mutable ↗, a = [5, 8, 6, 3, 2, 7, 2, 6]; sum(1..5), a[3] = 10, sum(1..5) → 26 33. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Do I need range answers while the array keeps changing, and can two halves' answers be merged into the answer for the whole?

Reach for it when

  • +range queries mixed with updates
  • +count elements smaller/greater than x seen so far
  • +inversions
  • +find first position with prefix >= k (descend)
  • +n, q up to 2e5-1e6

It fails when

  • ×No updates at alluse Prefix sums (or sparse table for min/max)
  • ×The merge isn't associativeuse Not a segment tree
  • ×Range updates, not just point updatesuse Lazy segment tree

Looks like it, isn't (and the other way round)

  • Count of Smaller Numbers After Self looks like Monotonic Stack, needs this pattern

    Counts of all smaller elements, not the nearest one: BIT over compressed values or merge-sort counting.

  • Minimum Number of Increments on Subarrays to Form a Target Array looks like Segment Tree / Fenwick (BIT), needs Difference Array & Line Sweep

    Divide-and-conquer on the minimum works, but the editorial's difference-array view gives the sum of positive rises in O(n).

  • Remainder Problem looks like Segment Tree / Fenwick (BIT), needs Square Root Decomposition

    'Sum over i = y mod x' has no segment-tree form. Precompute a table for x <= sqrt(N), brute force larger x.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1In the array layout, where are the root, the leaves and node i's children?Reveal

    Root t[1], leaves t[n..2n−1], children of i at 2i and 2i + 1.

  • 2Why does a point update cost O(log n)?Reveal

    Only the leaf's ancestors contain that element: one node per level, about log₂ n of them.

  • 3When is a Fenwick tree not enough?Reveal

    When the merge can't be undone, like range min or max: a range answer can't be a difference of two prefixes.

Practice ladder

every problem →
  1. 1Dynamic Range Sum Queriesthe frameMedium
  2. 2Range Sum Query - Mutablethe hookMedium
  3. 3Dynamic Range Minimum Queriesmerge = minMedium
  4. 4Hotel Querieswalk downMedium
  5. 5Count of Smaller Numbers After Selfindex by valueHard
  6. 6Josephus Problem IIwalk down to the k-th aliveHard
  7. 7Salary Queriescompressed countsMedium
  8. 8Range Updates and Sumsrange updatesMedium
  9. 9Reverse Pairsthe bossHard

Finished Segment Tree / Fenwick (BIT)? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Segment Tree / Fenwick (BIT)

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial