1. Brute Force — Array Conversion & Reconstruction
Intuition
Read all nodes of list1 into an array. Replace elements from index a to b with elements of list2. Rebuild a new linked list from the combined array.
Algorithm
- Step 1: Collect values of
list1intov1, and values oflist2intov2. - Step 2: Construct combined array:
v1[0 ... a-1] + v2 + v1[b+1 ... end]. - Step 3: Build a new linked list from the combined array and return its head.
#include <iostream>#include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}}; class Solution {public: ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { vector<int> v1, v2; for (ListNode* c = list1; c; c = c->next) v1.push_back(c->val); for (ListNode* c = list2; c; c = c->next) v2.push_back(c->val); vector<int> combined; for (int i = 0; i < a; ++i) combined.push_back(v1[i]); for (int val : v2) combined.push_back(val); for (int i = b + 1; i < (int)v1.size(); ++i) combined.push_back(v1[i]); ListNode* dummy = new ListNode(0); ListNode* curr = dummy; for (int val : combined) { curr->next = new ListNode(val); curr = curr->next; } ListNode* res = dummy->next; delete dummy; return res; }}; int main() { ListNode* l1 = new ListNode(10); l1->next = new ListNode(1); l1->next->next = new ListNode(13); l1->next->next->next = new ListNode(6); l1->next->next->next->next = new ListNode(9); l1->next->next->next->next->next = new ListNode(5); ListNode* l2 = new ListNode(100); l2->next = new ListNode(101); Solution sol; ListNode* merged = sol.mergeInBetween(l1, 3, 4, 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)— Extracts N elements from list1 and M elements from list2, splices in array, and creates new linked nodes in O(N + M). - Space complexity:
O(N + M)— Allocates array buffer of size N + M and allocates new node objects.
Why Brute Force Doesn't Scale:
Array conversions allocate O(N + M) memory buffer and discard existing pointer graph.
For N = 10,000 and M = 10,000, in-place splicing requires 0 extra bytes and finishes in <0.1ms.