Merge k Sorted Lists
heap • linked-list • divide-and-conquer
Hard
Merge k sorted linked lists and return it as one sorted list.
Examples
Input
[[1,4,5],[1,3,4],[2,6]]
Output
[1,1,2,3,4,4,5,6]
Merged list ordered.
Solution
Use a min-heap (priority queue) seeded with the head of each list.
Pop the smallest node, append to result, and if that node has next, push next into heap.
Time: where n is total nodes and k is number of lists. Space: for the heap.
Merge k Sorted Lists
heap • linked-list • divide-and-conquer
Hard
Merge k sorted linked lists and return it as one sorted list.
Examples
Input
[[1,4,5],[1,3,4],[2,6]]
Output
[1,1,2,3,4,4,5,6]
Merged list ordered.
Solution
Use a min-heap (priority queue) seeded with the head of each list.
Pop the smallest node, append to result, and if that node has next, push next into heap.
Time: where n is total nodes and k is number of lists. Space: for the heap.
Code Solution
merge-k-lists.cpp
cpp
1#include <vector>2#include <queue>3using namespace std;45struct ListNode { int val; ListNode* next; ListNode(int x): val(x), next(nullptr) {} };67struct Cmp { bool operator()(ListNode* a, ListNode* b) const { return a->val > b->val; } };89ListNode* mergeKLists(vector<ListNode*>& lists) {10priority_queue<ListNode*, vector<ListNode*>, Cmp> pq;11for (auto node : lists) if (node) pq.push(node);12ListNode dummy(0), *p = &dummy;13while (!pq.empty()) {14auto cur = pq.top(); pq.pop();15p->next = cur; p = p->next;16if (cur->next) pq.push(cur->next);17}18return dummy.next;19}