Merge K Sorted Lists

Merge k sorted linked lists using a min-heap of current heads.

Hard
Time O(N log k) Space O(k)
LeetCode
5 min read
k-way-merge heaps linked-list

Problem#

You are given k sorted linked lists. Merge them into one sorted linked list.

Examples#

  • [[1,4,5],[1,3,4],[2,6]][1,1,2,3,4,4,5,6]

Constraints#

  • 0 <= k <= 10^4, total nodes <= 10^4.

Approach#

Merge one at a time — O(k * N) total, where N is total node count.
Min-heap of heads — O(N log k). Each pop yields the next-smallest node; push its successor.

Solution#

Merge K Sorted Lists
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](ListNode* a, ListNode* b){ return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);
for (auto h : lists) if (h) pq.push(h);
ListNode dummy(0);
ListNode* tail = &dummy;
while (!pq.empty()) {
ListNode* top = pq.top(); pq.pop();
tail->next = top;
tail = top;
if (top->next) pq.push(top->next);
}
return dummy.next;
}
};

Editorial#

The heap always contains at most k candidates (one per list’s current head). Each pop extracts the global minimum; each push adds the popped node’s successor. Total N pop/push operations, each O(log k).

Complexity#

  • Time: O(N log k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.