Data Structures & AlgorithmsHardAmazon · Microsoft OA
Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current right-half element being merged in), how many inversions (pairs i < j with a[i] > a[j]) does [51, 53, 33, 13, 2, 44, 20] have?
- A. 15
- B. 16
- C. 14
- D. 6
Correct answer: A. 15
Whenever an element from the right half is merged in before some remaining left-half elements, every one of those remaining left elements forms an inversion with it; summing these counts across the whole merge sort gives 15 inversions, matching the O(n²) brute-force pair count.
More Coding Interview Problems questions
- Using the merge-sort inversion-count technique (count, during each merge step, how many left-half elements are greater than the current…
- What is the length of the longest common subsequence of "AEEBDCCC" and "BEBEADE"?
- Problem: A string s (length n) must be searched for a pattern p (length m) in text. Which algorithm guarantees O(n+m) worst-case time…
- Problem: Rabin-Karp pattern matching uses a rolling hash to compare a pattern against every window of the text. What is its typical time…
- Problem: Which traversal order is guaranteed to visit nodes level by level in a tree or graph?
- Problem: For a weighted graph with all non-negative edge weights, which algorithm finds shortest paths from a single source, and in what…