Friday, December 9, 2022

[Uber][LeetCode] Find K Pairs with Smallest Sums

Problem: You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

Example:

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [[1,1],[1,1]]
Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [[1,3],[2,3]]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]


Approach: The problem is straight forward. We can use Priority Queue / Heap to solve this problem.


Implementation in C#:

    public IList<IList<int>> KSmallestPairs(int[] nums1,
int[] nums2,
int k)
{
int length1 = nums1?.Length ?? 0;
int length2 = nums2?.Length ?? 0;
List<IList<int>> result = new List<IList<int>>();
if (length1 == 0 || length2 == 0)
{
return result;
}

PriorityQueue<int[], int> pq = new PriorityQueue<int[], int>();
for (int i = 0; i < length1 && i < k; ++i)
{
pq.Enqueue(new int[] {i, 0}, nums1[i] + nums2[0]);
}

while (pq.Count > 0 && result.Count < k)
{
int[] indices = pq.Dequeue();
result.Add(new List<int> {nums1[indices[0]],
                nums2[indices[1]]});
int index2 = indices[1] + 1;
if (index2 < length2)
{
pq.Enqueue(new int[] {indices[0], index2},
nums1[indices[0]] + nums2[index2]);
}
}
return result;
}

Complexity: klogk

No comments:

Post a Comment