Merge k Sorted Lists — LeetCode 23 Python Solution

HardLinked ListDivide and ConquerHeap (Priority Queue)Merge Sort
Problem
#23
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

Python
# 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

MeasureComplexity
TimeO(n \times \log k)
SpaceO(k) auxiliary

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

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

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 \times \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.

Get Stealth Interview