🎉 All 30 days are live — the full DSA-30 course, from Big-O to System Design. See the roadmap →
Day 19 - Segment TreesBasic Questions

Basic Segment Tree & BIT Questions

Six warm-ups to make the range-structure reflexes automatic: choosing the aggregate, the three-case query, the BIT loop, and the coordinate-compression preprocessing that unlocks half the hard problems.

1. Range sum with point updates

The canonical use. Build a sum segment tree (or a BIT); query(i, j) returns the subrange sum, update(i, v) changes a value — both O(log n). This is exactly Range Sum Query — Mutable. If you only need sums, prefer the BIT for its brevity.

2. Range minimum query (RMQ)

Same segment tree, different aggregate: combine = min, identity = +∞. Now query(i, j) is the smallest element in the subrange.

A BIT can’t do general RMQ (min isn’t invertible) — this is the textbook reason to choose a segment tree.

3. The BIT update/query loop by hand

Trace update(i, +1) walking up via i += i & -i and prefixSum(i) walking down via i -= i & -i. For n = 8, update(5, +1) touches indices 5 → 6 → 8; prefixSum(7) sums bit[7] + bit[6] + bit[4]. Doing one trace by hand makes the i & -i jumps click.

4. Count elements ≤ x seen so far (a frequency BIT)

A huge pattern: index the BIT by value instead of position. update(value, +1) records “I’ve seen this value”; prefixSum(x) counts how many seen values are ≤ x. This turns “how many earlier elements are smaller?” into a BIT query — the engine behind Count of Smaller Numbers After Self.

5. Coordinate compression

When values are huge or sparse (up to 10^9) but there are only n ≤ 10^5 of them, you can’t index a BIT by raw value. Compress: collect all values, sort + dedupe, and map each to its rank (0, 1, 2, …). Now index by rank — the BIT only needs size n.

This preprocessing is mandatory for value-indexed BIT/segment-tree problems with large ranges.

6. Range update via difference array

To “add v to all of [i, j]” with only point-update tooling, store deltas: update(i, +v), update(j+1, −v). A prefix sum then reconstructs the value at any index. The lightweight version of lazy propagation when you only need point reads after range updates.

Two reflexes separate people who “know segment trees” from people who use them: (1) index by value, not position, when the question is about counts/order statistics (“how many smaller”, “how many in range”); and (2) coordinate-compress the moment values are large but few. Most “hard” BIT problems are easy once you apply both.

Mini-quiz

To count, for each element, how many earlier elements are smaller, you index a BIT by VALUE and process left to right. What two operations per element?
Values range up to 10^9 but there are only 10^5 of them. Why coordinate-compress before using a value-indexed BIT?

Next: Practice Questions — eight interview classics across segment trees and BITs.