Data Structures & AlgorithmsHardProduct Company SDE · Amazon OA
Problem: What is the number of inversions in the array [6, 2, 8, 1, 9, 4, 3, 7, 5]? (An inversion is a pair of indices i < j with a[i] > a[j].)
- A. 17
- B. 5
- C. 19
- D. 36
Correct answer: A. 17
Counting, for each element, the smaller values to its right gives 5 + 1 + 5 + 0 + 4 + 1 + 0 + 1 = 17 (merge sort does it in O(n log n)). Counting only adjacent descents gives 5, counting a[i] < a[j] gives 36 − 17 = 19, and 36 counts every pair.
More Coding Interview Problems questions
- Problem: Using a single counter, a sequence of commands is applied to the value x = 0: "+5", "×2", "−3", "×2", "+1", "÷4" (integer…
- Problem: In a binary max-heap stored in an array with 1-based indexing, the array is [40, 30, 35, 10, 20, 25, 28, 5, 8, 12]. An operation…
- Problem: In the array [3, 8, 1, 9, 4, 7, 2, 6, 5], what is the length of the longest subarray whose sum is exactly 20?
- Problem: A sorted list 2, 4, 6, 8, 10, 12, 14 is treated as a rotated array: the first 3 values are moved to the end, giving 8, 10, 12…
- Problem: Four processes arrive at times 0, 2, 4, 6 with burst times 6, 2, 8, 3. The scheduler is shortest-remaining-time-first…
- Problem: In the grid of 0s and 1s below, count the number of 2×2 all-ones squares. 1110 1111 0111 1111