Skip to main content

Introduction

Range query data structures are fundamental in competitive programming for efficiently answering queries over array segments. These structures support operations like:
  • Range Sum/Min/Max: Find aggregate values over a range
  • Range Updates: Modify multiple elements efficiently
  • Point Queries: Access individual elements after updates

Segment Tree

Versatile tree structure supporting range queries and updates in O(log n)

Fenwick Tree

Memory-efficient structure for prefix sums and point updates

Sparse Table

Static RMQ with O(1) query time for idempotent operations

Choosing the Right Structure

Segment Tree

  • Best for: General range queries with range updates
  • Supports: Any associative operation
  • Updates: O(log n) point and range updates
  • Queries: O(log n)
  • Space: O(4n)

Fenwick Tree (BIT)

  • Best for: Prefix sums and frequency counting
  • Supports: Operations with inverse (addition/subtraction)
  • Updates: O(log n) point updates
  • Queries: O(log n) prefix queries
  • Space: O(n)

Sparse Table

  • Best for: Static arrays with idempotent operations
  • Supports: min, max, gcd (operations where f(x,x) = x)
  • Updates: Not supported (static)
  • Queries: O(1)
  • Space: O(n log n)

Common Use Cases

Idempotent Operations: An operation f is idempotent if f(x, x) = x. Examples include min, max, gcd, but NOT sum or xor.

Range Sum Queries

// Fenwick Tree - most efficient
fenwick<int> ft(n);
ft.modify(i, val);  // Add val to position i
int sum = ft.query(r) - ft.query(l-1);  // Sum [l, r]

Range Minimum Query (RMQ)

// Sparse Table - O(1) queries on static array
auto func = [](int x, int y) { return min(x, y); };
SparseTMin<int> st(values);
int min_val = st.query(l, r);  // O(1)

Range Updates with Lazy Propagation

// Segment Tree with lazy propagation
segtree<int> st(n);
st.modify(l, r, val);  // Set all elements in [l, r] to val
auto result = st.query(l, r);  // Get sum, min, max

Performance Comparison

StructureBuildPoint UpdateRange UpdatePoint QueryRange QuerySpace
Segment TreeO(n)O(log n)O(log n)O(log n)O(log n)O(4n)
Segment Tree (Lazy)O(n)O(log n)O(log n)O(log n)O(log n)O(4n)
Fenwick TreeO(n log n)O(log n)-O(log n)O(log n)O(n)
Sparse TableO(n log n)--O(1)O(1)O(n log n)

Next Steps

Explore specific implementations:
  1. Segment Tree - Learn about basic and lazy propagation variants
  2. Fenwick Tree - Master efficient prefix sum queries
  3. Sparse Table - Understand O(1) RMQ for static arrays

Build docs developers (and LLMs) love