#23
Merge K Sorted Lists
hard· Linked Listruns: 0You are given an array of k linked lists, each sorted in ascending order. Merge all the linked lists into one sorted linked list and return its head.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 862
class Solution:
def mergeKLists(self, 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(self._merge(l1, l2))
lists = merged
return lists[0]
def _merge(
self, 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 or l2
return dummy.next
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.