Data Structures19 sections · 729 units
Open in Course

Intro

Why wavelet trees matter

You have a sequence of values.

You need to answer queries like:

  • "How many values in positions [l,r][l, r] are between aa and bb?"
  • "What is the kk-th smallest value in range [l,r][l, r]?"
  • "How many times does value vv appear in range [l,r][l, r]?"

Brute force scans the range: O(n)O(n) per query.

With many queries, that's too slow. Wavelet trees answer these in O(logσ)O(\log \sigma) where σ\sigma is the number of distinct values.

For typical problems, σ106\sigma \leq 10^6, so queries take about 2020 operations. In this section, I'll show you how wavelet trees work, how to build them, and how to use them for range frequency, range quantile, and range counting queries.