1. Brute Force — Index Mapping via Linear Search
Intuition
First duplicate the linear chain using next pointers. Then, for each original node, count how many steps away its random pointer is, and take that many steps in the copied list to assign the random pointer.
Algorithm
- Step 1: Traverse the original list and copy all nodes using only
nextpointers. - Step 2: Store pointers to all original nodes and copied nodes in two indexed arrays.
- Step 3: For each original node
i, find the indexjof itsrandompointer in the original array. - Step 4: Set
copied[i].random = copied[j](or null ifrandomwas null). - Step 5: Return the head of the copied list.
#include <iostream>#include <vector> using namespace std; class Node {public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = nullptr; random = nullptr; }}; class Solution {public: Node* copyRandomList(Node* head) { if (!head) return nullptr; vector<Node*> orig, cloned; Node* curr = head; while (curr) { orig.push_back(curr); cloned.push_back(new Node(curr->val)); curr = curr->next; } for (int i = 0; i < orig.size(); i++) { if (i + 1 < orig.size()) cloned[i]->next = cloned[i + 1]; if (orig[i]->random) { for (int j = 0; j < orig.size(); j++) { if (orig[i]->random == orig[j]) { cloned[i]->random = cloned[j]; break; } } } } return cloned[0]; }}; int main() { Node* n1 = new Node(1); Node* n2 = new Node(2); n1->next = n2; n1->random = n2; n2->random = n2; Solution sol; Node* res = sol.copyRandomList(n1); cout << "Brute Force Copy Head: " << res->val << ", Random: " << res->random->val << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— For each of the N nodes, finding the index of its random pointer requires an O(N) traversal. - Space complexity:
O(N)— Requires arrays to store node references for index lookups.
Why Brute Force Doesn't Scale:
O(N2) index search becomes prohibitively slow on lists with 10,000+ nodes.
For a linked list with 1,000,000 nodes, the in-place interweaving method takes ~12ms and consumes zero auxiliary memory, whereas a hash map requires >80MB of hash bucket allocations.