</>

23. Merge k Sorted Lists

Hard NeetCode 150
Linked List Time O(KlogK) Space O(K)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Linked List
Time
O(KlogK)
Space
O(K)

Standard Solution (C++)

SummaryGiven k singly-linked sorted lists, merge all of them into one sorted linked list and return its head.

Approach
  • Use a min-heap (priority queue) seeded with the head of every non-null list; the heap always gives the globally smallest unprocessed node in O(log k) time.
  • Pop the minimum node, append it to the result, then push its successor (if any) back into the heap — this maintains the invariant that every list's remaining front is represented.
  • A dummy sentinel node simplifies head-pointer bookkeeping, avoiding a special-case for the first node.
  • Total work is O(N log k) where N is the total number of nodes across all lists and k is the number of lists.
#include <vector>
#include <queue>
using namespace std;

// 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) {
        // Min-heap: smallest val has highest priority.
        auto cmp = [](ListNode* a, ListNode* b) {
            return a->val > b->val;
        };
        priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);

        // Seed the heap with each list's head (skip nulls).
        for (ListNode* head : lists) {
            if (head) pq.push(head);
        }

        ListNode dummy(0);
        ListNode* tail = &dummy;

        while (!pq.empty()) {
            // Grab the current global minimum.
            ListNode* node = pq.top(); pq.pop();
            tail->next = node;
            tail = tail->next;

            // Advance that list's pointer into the heap.
            if (node->next) pq.push(node->next);
        }

        return dummy.next;
    }
};
Time O(N log k) Space O(k)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (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) {
        int listNum=lists.size();
        for(int i=listNum-1; i>=0; i--){
            if(lists[i]==nullptr)
                lists.erase(lists.begin()+i);
        }

        if(lists.empty())
            return nullptr;

        auto comp = [](ListNode* a, ListNode* b){
            return a->val > b->val; // Min-heap logic
        };

        std::priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq(comp);
        for(ListNode* head: lists){
            pq.push(head);
        }

        ListNode dummy(0);
        ListNode* cur=&dummy;
        
        while(!pq.empty()){
            ListNode* minNode=pq.top();
            pq.pop();

            cur->next=minNode;
            cur=cur->next;

            if(minNode->next){
                pq.push(minNode->next);
            }
        }

        return dummy.next;
    }
};

// Time Complexity: O(KlogK) for initializing the priority queue, and O(NlogK) for the while loop. So total time complexity is O(NlogK).
// Space Complexity: O(K) for the priority queue.
Time O(KlogK) Space O(K)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern