Problems > Distinct Values in Ranges > Editorial

Distinct Values in Ranges — Solution & Editorial

Back to the Problem

Offline by right endpoint: sweep r left-to-right keeping, for every value, a 1 only at its LAST occurrence (moving it forward as the value reappears) in a Fenwick tree. A query (l, r) is then the range sum — each distinct value in [l, r] contributes exactly its last occurrence.

Complexity: O((N + Q) log N)

Watch out: The last-occurrence trick is the entire problem; Mo's algorithm also works but is a constant-factor gamble in slow languages.