Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the inversions of an array with merge sort.
Problem: Count the inversions of an array with merge sort.
def inv(a):
if len(a) < 2: 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([8, 4, 2, 1])[1], inv([3, 1, 2, 3, 0])[1], inv([1, 1, 1])[1])What is printed?- A. 6 5 0
- B. 4 6 0
- C. 6 6 0
- D. 6 6 3
Correct answer: C. 6 6 0
When R[j] is placed before the remaining L[i:], it forms an inversion with each of them: add len(L) − i. [8, 4, 2, 1] is fully reversed → C(4,2) = 6. [3, 1, 2, 3, 0]: (3,1), (3,2), (3,0), (1,0), (2,0), (3,0) → 6. Using < instead of <= would count equal pairs as inversions. O(n log n).
More Coding Interview Problems questions
- Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed). python def…
- Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed). cpp int n = 8; vector<long long> t(n + 1, 0); void…
- Problem: Range minimum queries with a sparse table after O(n log n) preprocessing. python a = [7, 2, 9, 4, 3, 8, 6, 1, 5] n = len(a); LOG…
- Problem: A segment tree stores range sums. How many nodes does the recursive query visit? python a = [1, 3, 5, 7, 9, 11, 13, 15] visits =…
- Problem: Count the board states reachable on a 2 × 2 sliding puzzle ('0' is the blank, which swaps with an adjacent tile), using BFS over…
- Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people. python def…