Problem
Given two sorted arrays, we can form a set of sums by adding one element from the first array and one from the second array. Find the N-th smallest element in the sorted order of this set of sums.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Priority Queue
To solve this problem efficiently, we can use a min-heap (priority queue). The basic idea is to keep track of the smallest sums currently possible and gradually expand from there. Here are the steps:
- Initialize a min-heap (priority queue) to keep track of the smallest sums.
- Use a set to keep track of visited pairs to avoid duplication.
- Start with the smallest pair
(arr1[0] + arr2[0])
and expand by pushing the next potential smallest pairs into the heap. - Extract the smallest element from the heap N times to get the N-th smallest sum.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, because each insertion and extraction operation in the heap will take (O(\log N)) time, and we perform these operations up to N times. - 🧺 Space complexity:
O(N + min(N, m * m))
, wherem
andn
are the lengths of the two arrays.- O(N) from heap size