Command Palette

Search for a command to run...

← All patterns

Pattern · Trees

Range Queries (Fenwick & Segment Trees)

Answer sums, minimums or counts over any range while the array keeps changing, in O(log n) per query and update.

Time O(log n) per query and update · Space O(n)

Taught in Module 36: Advanced Data Structures

Think of it like this

A company's reporting chain: each manager keeps a running total for their team, so you add up a few managers' numbers instead of every employee's.

Clues that point here

  • → Range sum or minimum with point updates
  • → "Count smaller numbers after self"
  • → Many queries and updates interleaved
  • → Static range minimum (sparse table)

Not this pattern when

  • ✕ The array never changes and only sums are needed (prefix sums)
  • ✕ Only one query

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Range Queries (Fenwick & Segment Trees) · template
// Fenwick tree (1-indexed): prefix sums with point updates
int[] bit = new int[n + 1];
void add(int i, int delta) { for (i++; i <= n; i += i & -i) bit[i] += delta; }
int prefix(int i) { int s = 0; for (i++; i > 0; i -= i & -i) s += bit[i]; return s; }   // sum of [0..i]
int range(int l, int r) { return prefix(r) - (l > 0 ? prefix(l - 1) : 0); }

Common versions

  • Range sum query (mutable)
  • Count of smaller numbers after self
  • Range minimum (segment tree or sparse table)
  • Lazy propagation for range updates
  • Coordinate compression

Practice problems with this pattern

Related patterns