Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count inversions (i < j, a[i] > a[j]) with a Fenwick tree over values, scanning from the right.

Problem: Count inversions (i < j, a[i] > a[j]) with a Fenwick tree over values, scanning from the right.
def inversions(a):
    n = max(a); bit = [0] * (n + 1)
    def upd(i):
        while i <= n: bit[i] += 1; i += i & -i
    def qry(i):
        s = 0
        while i > 0: s += bit[i]; i -= i & -i
        return s
    inv = 0
    for x in reversed(a):
        inv += qry(x - 1)
        upd(x)
    return inv
print(inversions([5, 3, 8, 6, 1, 7, 2, 4]))
What is printed?
  1. A. 12
  2. B. 18
  3. C. 14
  4. D. 16

Correct answer: D. 16

Scanning right to left, qry(x − 1) counts the smaller values already seen to the right of x, i.e. the inversions that x starts. The total 16 matches checking all 28 pairs. Using qry(x) would also count equal values.

More Coding Interview Problems questions

Exams that ask this topic