1. Brute Force — Collect Node Values and Rebuild
Intuition
Traverse each list and store all node values in a dynamic array. Sort the array. Then create new linked list nodes for each value in sorted order.
When to apply: When pointer manipulation is tricky and extra memory is unconstrained.
Algorithm
- Step 1: Traverse all lists and push values into vector.
- Step 2: Sort vector ascending.
- Step 3: Build a new linked list from sorted values.
- Step 4: Return head of new linked list.
#include <iostream>#include <vector>#include <algorithm>using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* mergeKLists(vector<ListNode*>& lists) { vector<int> vals; for (auto list : lists) { while (list) { vals.push_back(list->val); list = list->next; } } sort(vals.begin(), vals.end()); ListNode dummy(0); ListNode* curr = &dummy; for (int v : vals) { curr->next = new ListNode(v); curr = curr->next; } return dummy.next; }}; int main() { Solution sol; ListNode* l1 = new ListNode(1); l1->next = new ListNode(4); ListNode* l2 = new ListNode(2); l2->next = new ListNode(3); vector<ListNode*> lists = {l1, l2}; ListNode* res = sol.mergeKLists(lists); cout << "Merged List (Brute Force): "; while (res) { cout << res->val << " "; res = res->next; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— O(N log N) from sorting. - Space complexity:
O(N)— O(N) memory to store values and new nodes.
Why Brute Force Doesn't Scale:
With K = 10,000 and total nodes N = 10,000, sequential merge takes ~108 operations. Min-Heap takes 10,000 * log(10,000) = ~1.3 * 105 operations (1000x faster).
Min-Heap merges 10,000 lists in ~12ms.