You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
is sorted in ascending order.lists[i].length
will not exceed 10^4
.How would you approach this problem and what is the most efficient solution?
One straightforward approach is to collect all the values from the linked lists into a single array, sort the array, and then construct a new linked list from the sorted array.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeKLists(lists):
values = []
for linked_list in lists:
current = linked_list
while current:
values.append(current.val)
current = current.next
values.sort()
if not values:
return None
head = ListNode(values[0])
current = head
for i in range(1, len(values)):
current.next = ListNode(values[i])
current = current.next
return head
A more efficient approach utilizes a priority queue (min-heap) to keep track of the smallest node among all linked lists. This avoids sorting the entire array at once and allows us to build the merged list in a sorted manner.
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeKLists(lists):
heap = []
for node in lists:
if node:
heapq.heappush(heap, (node.val, node))
dummy = ListNode()
current = dummy
while heap:
val, node = heapq.heappop(heap)
current.next = node
current = current.next
if node.next:
heapq.heappush(heap, (node.next.val, node.next))
return dummy.next
lists
is empty, return None
.None
).