0023. Merge k Sorted Lists

Hard | Linked List + Sort | 76 ms (98.81%), 22.3 MB (39.22%)

Source: LeetCode - Merge k Sorted Lists GitHub: Solution / Performance

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.

Extended question from LeetCode 0021. Merge Two Sorted Lists.

We could use the "Merge with Divide and Conquer" method for better performance. Generally speaking, we do merge starting with 2 lists per iteration, then increasing to 4 lists per iteration, etc.

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        # (base case)
        if len(lists) == 0: return None
        if len(lists) == 1: return lists[0]
        
        # ==================================================
        #  Linked List + Sort                              =
        # ==================================================
        # time  : O(nlogk)
        # space : O(1)
        # 
        # n is the total number of nodes in two linked lists
        # k is the number of linked lists
        
        size = 1
        while size < len(lists):
            for i in range(0, len(lists) - size, size * 2):
                lists[i] = self.merge2Lists(lists[i], lists[i+size])
            size *= 2
            
        return lists[0]
        
    def merge2Lists(self, l1: ListNode, l2: ListNode) -> ListNode:
        ret = ListNode(0)
        cur = ret
        
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = ListNode(l1.val)
                cur = cur.next
                l1 = l1.next
            else:
                cur.next = ListNode(l2.val)
                cur = cur.next
                l2 = l2.next
                
        cur.next = l1 or l2
                
        return ret.next

Last updated