Leetcode 373: Find K Pairs with Smallest Sums

grid47
grid47
Exploring patterns and algorithms
Sep 30, 2024 6 min read

A series of pairs of numbers, with the smallest sum softly glowing as each pair is tested.
Solution to LeetCode 373: Find K Pairs with Smallest Sums Problem

Given two sorted integer arrays nums1 and nums2 and an integer k, return the k pairs with the smallest sums. Each pair consists of one element from nums1 and one element from nums2.
Problem
Approach
Steps
Complexity
Input: The input consists of two sorted arrays, `nums1` and `nums2`, and an integer `k`.
Example: Input: nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3
Constraints:
• 1 <= nums1.length, nums2.length <= 10^5
• -10^9 <= nums1[i], nums2[i] <= 10^9
• nums1 and nums2 are sorted in non-decreasing order.
• 1 <= k <= 10^4
• k <= nums1.length * nums2.length
Output: Return a list of the `k` pairs with the smallest sums.
Example: Output: [[1, 2], [1, 4], [1, 6]]
Constraints:
• The pairs must be returned in non-decreasing order of their sums.
Goal: The goal is to find the `k` smallest sum pairs efficiently, leveraging the sorted order of the input arrays.
Steps:
• 1. Initialize a priority queue (min-heap) to track the smallest sums.
• 2. Push the first pair from each element in `nums1` and the first element in `nums2` into the priority queue.
• 3. Continue popping the smallest pairs and pushing the next possible pairs until `k` pairs are found.
Goal: The constraints on the size of the arrays and the value of `k` dictate the need for efficient algorithms.
Steps:
• The arrays `nums1` and `nums2` are sorted in non-decreasing order.
• k must be less than or equal to the number of possible pairs between `nums1` and `nums2`.
Assumptions:
• The arrays `nums1` and `nums2` are both sorted in non-decreasing order.
Input: Input: nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3 Output: [[1, 2], [1, 4], [1, 6]]
Explanation: The smallest pairs are (1, 2), (1, 4), and (1, 6) because their sums are 3, 5, and 7, respectively.

Input: Input: nums1 = [1, 1, 2], nums2 = [1, 2, 3], k = 2 Output: [[1, 1], [1, 1]]
Explanation: The first two pairs are (1, 1) and (1, 1) because their sums are both 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus