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?- A. 12
- B. 18
- C. 14
- 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
- Problem: Return the longest word that can be built one letter at a time from other words in the list (every prefix must be present); ties…
- Problem: s1[i] and s2[i] are declared equivalent letters (the relation is reflexive, symmetric and transitive). Replace every letter of…
- Problem: Find all roots that give a tree of minimum height, by repeatedly peeling off leaves. python def mht(n, edges): adj = [set() for…
- Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length)…
- Problem: Balloons span horizontal intervals [start, end]; an arrow shot at x bursts every balloon with start ≤ x ≤ end. Find the minimum…
- Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health…