1. Brute Force — Array Collection, Sort & Rebuild
Intuition
Read all elements from both lists into an array, sort the array, and build a brand new linked list.
Algorithm
- Step 1: Collect all values from
list1andlist2into arrayvals. - Step 2: Sort
valsin non-decreasing order. - Step 3: Construct a new linked list with
valsand return its head.
#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* mergeTwoLists(ListNode* list1, ListNode* list2) { vector<int> vals; for (ListNode* c = list1; c; c = c->next) vals.push_back(c->val); for (ListNode* c = list2; c; c = c->next) vals.push_back(c->val); sort(vals.begin(), vals.end()); ListNode* dummy = new ListNode(0); ListNode* curr = dummy; for (int val : vals) { curr->next = new ListNode(val); curr = curr->next; } ListNode* res = dummy->next; delete dummy; return res; }}; int main() { ListNode* l1 = new ListNode(1); l1->next = new ListNode(2); l1->next->next = new ListNode(4); ListNode* l2 = new ListNode(1); l2->next = new ListNode(3); l2->next->next = new ListNode(4); Solution sol; ListNode* merged = sol.mergeTwoLists(l1, l2); cout << "Brute Force Merged: "; for (ListNode* c = merged; c; c = c->next) cout << c->val << (c->next ? " -> " : ""); cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O((N + M) log(N + M))— Extracts N + M values into an array, sorts in O((N+M) log(N+M)), and creates new nodes in O(N+M). - Space complexity:
O(N + M)— Allocates array buffer and fresh nodes for all elements.
Why Brute Force Doesn't Scale:
Array sorting runs in O((N+M) log(N+M)) time and allocates O(N+M) space.
For N = 100,000 and M = 100,000, iterative merge takes <1ms and 0 heap allocations.