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

Problem: Count the inversions of an array with merge sort.

Problem: Count the inversions of an array with merge sort.
def inv(a):
    if len(a) < 2: return a, 0
    m = len(a) // 2
    L, x = inv(a[:m]); R, y = inv(a[m:])
    out, i, j, c = [], 0, 0, x + y
    while i < len(L) and j < len(R):
        if L[i] <= R[j]: out.append(L[i]); i += 1
        else: out.append(R[j]); j += 1; c += len(L) - i
    return out + L[i:] + R[j:], c
print(inv([8, 4, 2, 1])[1], inv([3, 1, 2, 3, 0])[1], inv([1, 1, 1])[1])
What is printed?
  1. A. 6 5 0
  2. B. 4 6 0
  3. C. 6 6 0
  4. D. 6 6 3

Correct answer: C. 6 6 0

When R[j] is placed before the remaining L[i:], it forms an inversion with each of them: add len(L) − i. [8, 4, 2, 1] is fully reversed → C(4,2) = 6. [3, 1, 2, 3, 0]: (3,1), (3,2), (3,0), (1,0), (2,0), (3,0) → 6. Using < instead of <= would count equal pairs as inversions. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic