Python: Find k number of pairs which consists of one element from the first array and one element from the second array
17. K Pairs from Two Sorted Arrays
You have two integer arrays sorted in ascending order and an integer k. Write a Python program to find k number of pairs (u, v) which consist of one element from the first array and one element from the second array using the heap queue algorithm.
Sample Solution:
Python Code:
Sample Output:
[[1, 2], [1, 4]]
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to merge two sorted arrays into k pairs with the smallest sums using a min-heap and then print the resulting pairs.
- Write a Python script to generate k pairs (u, v) from two sorted arrays using heapq and then validate that these pairs have the smallest combined values.
- Write a Python program to implement a function that takes two sorted lists and an integer k, and returns the k pairs with the smallest sum using a heap.
- Write a Python function to use a min-heap to find the k smallest pairs from two arrays and then output the pairs along with their sum.
Go to:
Previous: Write a Python program which add integer numbers from the data stream to a heapq and compute the median of all elements.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.