PracticeNeetCode ↗LeetCode ↗
Given an array of k sorted linked lists, merge them into one sorted linked list and return its head.
None.Time: O(n log k) where n is total nodes, k is number of lists — Space: O(log k) for the merge rounds
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1: ListNode | None, l2: ListNode | None) -> ListNode | None:
dummy = ListNode()
tail = dummy
while l1 and l2:
if l1.val <= l2.val:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next
tail.next = l1 if l1 else l2
return dummy.next
def mergeKLists(lists: list[ListNode | None]) -> ListNode | None:
if not lists:
return None
while len(lists) > 1:
merged = []
for i in range(0, len(lists), 2):
l1 = lists[i]
l2 = lists[i + 1] if i + 1 < len(lists) else None
merged.append(mergeTwoLists(l1, l2))
lists = merged
return lists[0]How the solution above works, piece by piece.
mergeTwoLists is the standard two-list merge with a dummy head.while len(lists) > 1: each round pairs up lists 0+1, 2+3, …; an odd one out is merged with None, which just returns it.lists = merged: the next round works on half as many lists.Running it on lists = [[1, 4, 5], [1, 3, 4], [2, 6]]: