Data Structures & AlgorithmsVery hardProduct company OA

Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed?

Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed?
def inv(a):
    if len(a) <= 1: 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([5, 3, 8, 3, 1, 9, 2])[1], inv([4, 4, 4])[1], inv(list(range(10, 0, -1)))[1])
  1. A. 12 3 45
  2. B. 12 0 45
  3. C. 11 0 45
  4. D. 12 0 55

Correct answer: B. 12 0 45

When R[j] is taken before L[i], it is smaller than every remaining element of L, so it adds len(L) − i inversions at once – O(n log n) instead of O(n²). [5,3,8,3,1,9,2]: brute force confirms 12. Equal values are not inversions, and the merge takes from L on ties (≤), so [4,4,4] gives 0; using < there would count equal pairs and give 3. A reversed array of 10 has C(10, 2) = 45.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic