Introduction
Copy List with Random Pointer means creating a completely separate duplicate linked list.
Each node contains:
- next pointer
- random pointer
The task is to:
- create new nodes
- preserve next links
- preserve random links
Example:
Input:
1 -> 2 -> 3
Random:
1 -> 3
2 -> 1
3 -> 2
Output:
Deep copied list with same structure
Explanation:
New nodes are created. Original list remains unchanged.Both next and random connections are preserved.This problem is one of the most important applications of:
HashMap + Pointer ManipulationConstraints
0 <= Number of Nodes <= 10^5Approach 1 : Brute Force (Using HashMap)
Explanations:
Explanation:
The idea is:
- create copy of every node
- store mapping in HashMap
- reconnect next and random pointers
Steps:
- Copy all nodes.
- Store original -> copy mapping.
- Connect next pointers.
- Connect random pointers.
This is the most common interview solution.
Dry Run
Original:1 -> 2 -> 3
Copy nodes:
1' 2' 3'
Map:
1 -> 1'
2 -> 2'
3 -> 3'
Random links are copied using HashMap.
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :
Each node is visited twice.
Space Complexity:- O(n) Explanation :
HashMap stores node mapping.
Approach 2 : Optimal Solution(Using Interleaving Technique)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- insert copied nodes beside originals
- connect random pointers
- separate copied list
This avoids extra HashMap usage.
Dry Run
Original:
1 -> 2 -> 3
Insert copies:
1 -> 1' -> 2 -> 2' -> 3 -> 3'
Connect random pointers.
Separate copied list.Deep copy completed.
Practice :