Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: For each element of an array of n = 10⁵, count how many elements to its right are smaller. What is the best complexity?

  1. A. O(n) with a monotonic stack
  2. B. O(n²) is required
  3. C. O(n log n) by sorting once and reading positions
  4. D. O(n log n) using a Fenwick tree over compressed values scanned from the right (or merge sort with index tracking)

Correct answer: D. O(n log n) using a Fenwick tree over compressed values scanned from the right (or merge sort with index tracking)

Scanning from the right, insert each value into a BIT and query how many inserted values are smaller: O(log n) each. A monotonic stack finds the NEAREST smaller element, not the count. Sorting alone loses the 'to the right' constraint.

More Coding Interview Problems questions

Exams that ask this topic