Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Given n = 5 × 10⁴ integers, count pairs i < j with a[i] > 2·a[j]. Which approach is correct and efficient?
- A. Modified merge sort: before merging two sorted halves, count with a two-pointer sweep, O(n log n)
- B. Sort the array, then use two pointers on the sorted copy, O(n log n)
- C. Prefix sums of the array plus binary search, O(n log n)
- D. A hash map of values seen so far, O(n)
Correct answer: A. Modified merge sort: before merging two sorted halves, count with a two-pointer sweep, O(n log n)
The condition depends on index order, so sorting the whole array first destroys the i < j information. Merge sort keeps each half's original indices on one side, so for every element of the right half you count left-half values > 2·a[j] with a moving pointer before merging. A hash map cannot answer an inequality query.
More Coding Interview Problems questions
- Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java). python def…
- Problem: Sum the minimum of every contiguous subarray using a monotonic stack (previous-less and next-less-or-equal boundaries). python…
- Problem: Count the distinct non-empty substrings of a short string. python s = "ababa" print(len({s[i:j] for i in range(len(s)) for j in…
- Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix). python def…
- Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0). python…
- Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet…