0 out of 464 challenges solved
Write a Python function `k_smallest_pairs(nums1, nums2, k)` that takes two lists of integers `nums1` and `nums2`, and an integer `k`. The function should return the `k` smallest pairs (in terms of their sums) where each pair consists of one element from `nums1` and one element from `nums2`. If there are fewer than `k` pairs possible, return all possible pairs. #### Example Usage ```python [main.nopy] nums1 = [1, 3, 7] nums2 = [2, 4, 6] k = 2 print(k_smallest_pairs(nums1, nums2, k)) # Output: [[1, 2], [1, 4]] nums1 = [1, 3, 7] nums2 = [2, 4, 6] k = 7 print(k_smallest_pairs(nums1, nums2, k)) # Output: [[1, 2], [1, 4], [3, 2], [1, 6], [3, 4], [3, 6], [7, 2]] ``` #### Constraints - Both `nums1` and `nums2` are sorted in ascending order. - `k` is a non-negative integer. - The function should aim for efficiency, especially for large inputs.
import heapq def k_smallest_pairs(nums1, nums2, k): """ Find the k smallest pairs from two sorted arrays. Args: nums1 (List[int]): First sorted list of integers. nums2 (List[int]): Second sorted list of integers. k (int): Number of smallest pairs to find. Returns: List[List[int]]: List of k smallest pairs. """ # Placeholder for the solution pass