K Linked Lists

Phase

-
Current operation

Active Pair

-
Lists being merged

Depth

0
Recursion level

K

0
Number of lists
Click "Step" or "Play" to start merging the k sorted lists
Inactive
Active
Comparing
Merged
Python Code - Merge K Sorted Lists
def mergeKLists(lists):
    if not lists:
        return None
    if len(lists) == 1:
        return lists[0]
    mid = len(lists) // 2
    left = mergeKLists(lists[:mid])
    right = mergeKLists(lists[mid:])
    return _merge(left, right)
 
def _merge(first, second):
    dummy = ListNode()
    tail = dummy
    while first and second:
        if first.val < second.val:
            tail.next = first; first = first.next
        else:
            tail.next = second; second = second.next
        tail = tail.next
    tail.next = first or second
    return dummy.next