Data Structures & AlgorithmsHardProduct Company SDE · merge sort round

Problem: Find the number of inversions in [5, 4, 3, 2, 1] that a merge-sort based counter would report. Run the code.

Problem: Find the number of inversions in [5, 4, 3, 2, 1] that a merge-sort based counter would report. Run the code.
def count(a):
    if len(a) <= 1:
        return a, 0
    m = len(a) // 2
    l, x = count(a[:m])
    r, y = count(a[m:])
    res, c = [], x + y
    i = j = 0
    while i < len(l) and j < len(r):
        if l[i] <= r[j]:
            res.append(l[i]); i += 1
        else:
            res.append(r[j]); j += 1
            c += len(l) - i
    res += l[i:] + r[j:]
    return res, c
print(count([5, 4, 3, 2, 1])[1])
What is printed?
  1. A. 9
  2. B. 6
  3. C. 10
  4. D. 15

Correct answer: C. 10

A reversed array of size 5 has every pair inverted, which is C(5,2) = 10. The merge step adds the count of left elements still remaining whenever a right element is placed first.

More Coding Interview Problems questions

Exams that ask this topic