Data Structures & AlgorithmsHardICPC regional · Fenwick round

Problem: Count inversions in [2, 4, 1, 3, 5] with a Fenwick tree over the values.

Problem: Count inversions in [2, 4, 1, 3, 5] with a Fenwick tree over the values.
def inv(a):
    n = max(a)
    t = [0] * (n + 1)
    def add(i):
        while i <= n:
            t[i] += 1
            i += i & -i
    def q(i):
        s = 0
        while i > 0:
            s += t[i]
            i -= i & -i
        return s
    res = 0
    for seen, x in enumerate(a):
        res += seen - q(x)
        add(x)
    return res
print(inv([2, 4, 1, 3, 5]))
What is printed?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: B. 3

The inversions are (2,1), (4,1) and (4,3). Each step counts earlier elements that are greater than x as seen minus the number of earlier values at most x.

More Coding Interview Problems questions

Exams that ask this topic