KatInterview

23. Merge k Sorted Lists

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

This problem asks us to merge k sorted linked lists into a single sorted linked list. A naive approach of collecting all nodes and sorting them would work, but we can do better by leveraging the fact that the input lists are already sorted. The most efficient and common solutions involve either a Priority Queue (Min-Heap) or a Divide and Conquer strategy.

Solution

Merge k Sorted Lists in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
import heapq

class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        # min_heap will store tuples of (value, counter, node).
        # The counter is a tie-breaker to handle nodes with the same value,
        # as ListNode objects themselves are not comparable.
        min_heap = []
        counter = 0

        # Push the head of each non-empty list into the min-heap.
        for l in lists:
            if l:
                heapq.heappush(min_heap, (l.val, counter, l))
                counter += 1

        # A dummy head to simplify the construction of the merged list.
        dummy = ListNode(0)
        current = dummy

        # While there are still nodes to process in the heap.
        while min_heap:
            # Pop the node with the smallest value.
            val, _, node = heapq.heappop(min_heap)

            # Append this node to our result list.
            current.next = node
            current = current.next

            # If the popped node has a next node, push it to the heap.
            if node.next:
                heapq.heappush(min_heap, (node.next.val, counter, node.next))
                counter += 1

        # The merged list starts from the node after the dummy head.
        return dummy.next

Merge k Sorted Lists in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }

        // PriorityQueue in Java is a min-heap by default.
        // We provide a comparator to order nodes by their value.
        PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);

        // Add the head of each non-empty list to the priority queue.
        for (ListNode list : lists) {
            if (list != null) {
                pq.add(list);
            }
        }

        // A dummy head to simplify the construction of the merged list.
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        // While there are still nodes to process in the queue.
        while (!pq.isEmpty()) {
            // Get the node with the smallest value.
            ListNode minNode = pq.poll();

            // Append it to our result list.
            current.next = minNode;
            current = current.next;

            // If the extracted node has a next node, add it to the queue.
            if (minNode.next != null) {
                pq.add(minNode.next);
            }
        }

        // The merged list starts from the node after the dummy head.
        return dummy.next;
    }
}

Merge k Sorted Lists in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // Custom comparator for the priority queue. It will be a min-heap.
        auto cmp = [](ListNode* a, ListNode* b) {
            return a->val > b->val;
        };

        // The priority queue will store the head nodes of the lists.
        // It is a min-heap of ListNode pointers, ordered by the node's value.
        priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);

        // Push the head of each non-empty list into the min-heap.
        for (ListNode* list : lists) {
            if (list) {
                pq.push(list);
            }
        }

        // A dummy head to simplify the construction of the merged list.
        ListNode* dummy = new ListNode(0);
        ListNode* current = dummy;

        // While there are still nodes to process in the heap.
        while (!pq.empty()) {
            // Get the node with the smallest value from the heap.
            ListNode* minNode = pq.top();
            pq.pop();

            // Append this node to our result list.
            current->next = minNode;
            current = current->next;

            // If the extracted node has a next node, push it to the heap.
            if (minNode->next) {
                pq.push(minNode->next);
            }
        }
        
        // The merged list starts from the node after the dummy head.
        ListNode* result = dummy->next;
        delete dummy; // Clean up the dummy node.
        return result;
    }
};

Merge k Sorted Lists in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

// This solution uses a Divide and Conquer approach, which is equally optimal (O(N log k))
// and avoids implementing a Priority Queue from scratch in TypeScript/JavaScript.

function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
    if (!lists || lists.length === 0) {
        return null;
    }

    // Helper function to merge two sorted linked lists.
    const mergeTwoLists = (l1: ListNode | null, l2: ListNode | null): ListNode | null => {
        const dummy = new ListNode(0);
        let current = dummy;

        while (l1 && l2) {
            if (l1.val < l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }

        // Append the remaining part of the non-empty list.
        current.next = l1 || l2;

        return dummy.next;
    };

    let amount = lists.length;
    if (amount === 0) return null;
    
    // Iteratively merge lists. The interval doubles in each pass.
    // Pass 1: merge lists 2 by 2. (0,1), (2,3), ...
    // Pass 2: merge lists 4 by 4. (0,2), (4,6), ...
    // And so on, until all lists are merged into lists[0].
    let interval = 1;
    while (interval < amount) {
        for (let i = 0; i < amount - interval; i += interval * 2) {
            lists[i] = mergeTwoLists(lists[i], lists[i + interval]);
        }
        interval *= 2;
    }

    return lists[0];
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.