Data Structures19 sections · 729 units
Open in Course

Merge K Lists - Implementation

Complete solution

Here's the solution:

function mergeKLists(lists)
    heap := empty min-heap of (value, listIndex, node)

    // Initialize with first node from each list
    for i from 0 to length of lists - 1
        if lists[i] is not null
            insert (lists[i].val, i, lists[i]) into heap

    dummy := new ListNode(0)
    current := dummy

    while heap is not empty
        (val, idx, node) := extract min from heap
        current.next := node
        current := current.next

        if node.next is not null
            insert (node.next.val, idx, node.next) into heap

    return dummy.next

Time: O(nlogk)O(n \log k). Space: O(k)O(k).