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?
- A. Modified merge sort counting cross-half inversions, or a Fenwick tree over compressed values – O(n log n)
- B. Two nested loops – O(n²)
- C. Sort and compare positions – O(n) after sorting
- 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
- Problem: Answer q = 10⁵ queries 'sum of a[l..r]' on a static array of n = 10⁵ values. Which approach is best?
- Problem: An array of n = 10⁵ values receives 10⁵ operations, each either 'add v to a[i]' or 'sum of a[l..r]'. Which data structure gives…
- Problem: n ≤ 18 cities, find the shortest route visiting every city exactly once (travelling salesman). Which approach fits?
- Problem: n = 10⁵ intervals; for each, count how many other intervals it overlaps. What is the best complexity?
- Problem: A function does for i in range(n): for j in range(i, n, i + 1): work(). What is its time complexity?
- Problem: A recursive function on n does O(1) work and makes two calls on n/2. What is T(n)?