HardNo. 0023

Merge k Sorted Lists — LeetCode 23 Python Solution

Topics
Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort
Reading time
3 min

The problem

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.

Example

Input
lists = [[1,4,5],[1,3,4],[2,6]]
Output
[1,1,2,3,4,4,5,6]
Explanation
The linked-lists are:

Python solution

PythonSolution
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        setattr(ListNode, "__lt__", lambda a, b: a.val < b.val)
        pq = [head for head in lists if head]
        heapify(pq)
        dummy = cur = ListNode()
        while pq:
            node = heappop(pq)
            if node.next:
                heappush(pq, node.next)
            cur.next = node
            cur = cur.next
        return dummy.next

Complexity

Time
O(n × log k)
Space · auxiliary
O(k)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 23. Merge k Sorted Lists is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 23. Merge k Sorted Lists?

LeetCode 23. Merge k Sorted Lists is rated Hard on LeetCode.

What is the time complexity of LeetCode 23. Merge k Sorted Lists?

The Python solution on this page runs in O(n × log k).

What is the space complexity of LeetCode 23. Merge k Sorted Lists?

The Python solution on this page uses O(k) auxiliary space.

What topics does LeetCode 23. Merge k Sorted Lists cover?

LeetCode 23. Merge k Sorted Lists is tagged Linked List, Divide and Conquer, Heap (Priority Queue) and Merge Sort on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.