Data Structures19 sections · 729 units
Open in Course

The Range Counting Problem

Why standard tools fail

Given array AA of length nn, answer queries: "count elements in A[l..r]A[l..r] with value in [a,b][a, b]."

Attempt 1: Segment tree per value Build a segment tree for each distinct value.

Query: sum of counts in [l,r][l, r] for values aa to bb.

Problem: O(σ)O(\sigma) segment trees uses too much memory.

Attempt 2: Merge sort tree Build a segment tree where each node stores the sorted array of values in its range.

Problem: O(nlogn)O(n \log n) space and O(log2n)O(\log^2 n) query time.

Wavelet tree solution: O(nlogσ)O(n \log \sigma) space, O(logσ)O(\log \sigma) queries. Same or better space, faster queries.