Two sorted arrays are given. We have to find the K smallest products from the pairs from these arrays. I could think of a mnlogk solution but this solution works even if the arrays are not in sorted order. Can we make use of this sorted order and find a better solution?
I tried using max heap of size k for obtaining the mnlogk solution.
Input: nums1 = [-2, -1, 0, 1, 2], nums2 = [-3, -1, 2, 4, 5], k = 3 Output: [-10, -8, -6] Explanation: -2 * 5, -2 * 4, 2 * -3
Merge the Two Arrays. Similar to one single step of the Merge Sort sorting algorithm, we can merge the two arrays and then directly retrieve the kth element. The basic idea of the merge algorithm is to start with two pointers, which point to the first elements of the first and second arrays (a).
Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.
Instead of using the heap, try to generate products in the sorted order.
Imagine an n*m
grid formed by indices into the respective arrays. At any given point of time the grid is partitioned into the "inspected" and "not yet inspected" parts. We shall keep an invariant, namely that a product of every inspected pair is less than the product of a not inspected. The hard part is to prove that the border separating them has O(n+m)
pairs; the fact that the arrays are sorted is essential for the proof.
Now, you may test the products along the border, take the minimal, and modify the border accordingly. This operation will take O(n+m)
time, and would be performed k
times. An overall complexity is O(k(n+m)
).
And the final optimization: the above plan recomputes many products along the border over and over again. Representing the border as a sorted map may drive the complexity down to O(k log(n+m))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With