Data Structures & AlgorithmsHardProduct Company SDE · merge sort round
Problem: Find the number of inversions in [5, 4, 3, 2, 1] that a merge-sort based counter would report. Run the code.
Problem: Find the number of inversions in [5, 4, 3, 2, 1] that a merge-sort based counter would report. Run the code.
def count(a):
if len(a) <= 1:
return a, 0
m = len(a) // 2
l, x = count(a[:m])
r, y = count(a[m:])
res, c = [], x + y
i = j = 0
while i < len(l) and j < len(r):
if l[i] <= r[j]:
res.append(l[i]); i += 1
else:
res.append(r[j]); j += 1
c += len(l) - i
res += l[i:] + r[j:]
return res, c
print(count([5, 4, 3, 2, 1])[1])What is printed?- A. 9
- B. 6
- C. 10
- D. 15
Correct answer: C. 10
A reversed array of size 5 has every pair inverted, which is C(5,2) = 10. The merge step adds the count of left elements still remaining whenever a right element is placed first.
More Coding Interview Problems questions
- Problem: Which claim about the Knuth-Morris-Pratt algorithm is correct?
- Problem: A player picks a number from 1 to 10 and the other player must guess it by yes/no questions. The minimum worst-case number of…
- Problem: What is the complexity of computing all prefix XOR values of an array of n = 10^6 integers and then answering q = 10^6 range-XOR…
- Problem: Consider a DP over subsets for assigning n jobs to n workers (cost matrix given), with state = mask of assigned jobs and…
- Problem: A string of length n is built using the operation 'append the reverse of the current string'. Starting with 'a', the length after…
- Problem: Which statement about Dijkstra's algorithm using a binary heap with lazy deletion (pushing duplicate entries and skipping stale…