Data Structures & AlgorithmsHardProduct Company SDE · CP practice
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 [5, 33, 25, 58, 49, 37, 30] have?
- A. 13
- B. 7
- C. 9
- D. 8
Correct answer: D. 8
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 8 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…
- 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?