Write an efficient code to clone a linked list with each node containing an additional random pointer. The random pointer can point to any random node of the linked list or null.

Practice this problem

1. Linear time solution using extra space

To clone a linked list with random pointers, maintain a hash table for storing the mappings from a linked list node to its clone. We create a new node with the same data for each node in the original linked list and recursively set its next pointers. We also create a mapping from the original node to the duplicate node in the hash table. Finally, traverse the original linked list again and update the duplicate nodes’ random pointers using the hash table.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Original linked list:
1(4) —> 2(X) —> 3(2) —> 4(X) —> 5(X) —> null
 
Cloned linked list:
1(4) —> 2(X) —> 3(2) —> 4(X) —> 5(X) —> null

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and requires O(n) extra space for the map and call stack.

2. Linear time solution using constant space

A hash table is used in the previous approach, which accounts for the O(n) space complexity. We can improve the space complexity to constant if we find a space-efficient way to track the new nodes. We can do this by linking the new nodes with their original nodes in the linked list itself.

The idea is to create a duplicate of each linked list node and associate each duplicate node with the original node’s next child. Then iterate the modified list and update the random pointers of the new nodes. Finally, extract the duplicate nodes from the modified list, hence restoring the original linked list.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Original linked list:
1(4) —> 2(X) —> 3(2) —> 4(X) —> 5(X) —> null
 
Cloned linked list:
1(4) —> 2(X) —> 3(2) —> 4(X) —> 5(X) —> null