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

Problem: Count pairs (i < j) with a[i] > a[j] (inversions) in an array of n = 2 × 10⁵ values. Which approach runs within a 1-second limit?

  1. A. Modified merge sort counting cross-half inversions, or a Fenwick tree over compressed values – O(n log n)
  2. B. Two nested loops – O(n²)
  3. C. Sort and compare positions – O(n) after sorting
  4. D. A hash map of values – O(n)

Correct answer: A. Modified merge sort counting cross-half inversions, or a Fenwick tree over compressed values – O(n log n)

O(n²) is 2 × 10¹⁰ comparisons – far too slow. During merging, whenever an element from the right half goes first, it forms inversions with every remaining element of the left half, so all cross pairs are counted in O(n) per level. Hashing loses the order relationship that inversions depend on.

More Coding Interview Problems questions

Exams that ask this topic