Data Structures & AlgorithmsVery hardProduct company OA

Problem: n ≤ 2·10⁵ values and q ≤ 2·10⁵ offline queries 'how many DISTINCT values are in a[l..r]?' (time limit 2 s). Which approach is correct and fast enough?

  1. A. For each query build a set of a[l..r] – O(n) per query is fine because sets are O(1)
  2. B. Prefix counts of distinct values: answer = distinct(r) − distinct(l − 1)
  3. C. A segment tree storing the number of distinct values in each node, merged by adding the children's counts
  4. D. Sort queries by r; sweep r, and for each value keep only its LAST occurrence marked in a Fenwick tree (unmark the previous one); the answer is the BIT sum over [l, r] – O((n + q) log n)

Correct answer: D. Sort queries by r; sweep r, and for each value keep only its LAST occurrence marked in a Fenwick tree (unmark the previous one); the answer is the BIT sum over [l, r] – O((n + q) log n)

Per-query sets are O(n·q) = 4·10¹⁰ in the worst case. Distinct counts are not additive: a value present in both halves (or in both prefixes) is counted twice, so neither prefix differences nor summing children works. Keeping only the last occurrence makes each value contribute exactly once to any window ending at the current r, and that window's count is then a plain range sum. Mo's algorithm (O((n + q)√n)) also passes; the BIT sweep is simpler and faster.

More Coding Interview Problems questions

Exams that ask this topic