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?
- A. For each query build a set of a[l..r] – O(n) per query is fine because sets are O(1)
- B. Prefix counts of distinct values: answer = distinct(r) − distinct(l − 1)
- C. A segment tree storing the number of distinct values in each node, merged by adding the children's counts
- 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
- Problem: boxes (w, h) can nest when BOTH dimensions are strictly smaller. Find the longest nesting chain for n ≤ 2·10⁵. A candidate sorts…
- Problem: union–find runs m = 10⁶ operations on n = 10⁶ elements. Version X uses union by rank AND path compression; version Y uses path…
- Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all…
- Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time…
- Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a…
- Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back…