Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list.

The intuitive approach is to use a hash map to store the mapping between the original nodes and the copied nodes. The following code requires O(2n) in time and O(n) in space.

If we do not want to use extra memory, the following approach could be applied:
  1.  Copy the list nodes and insert the copied node right after the original node. For example, A->B->C->... becomes A->copyA->B->copyB->C->copyC->...
  2. If A has a non-null random pointer, we can simply set A->next->random = A->random->next.
  3. Split the list into two separate lists.
O(3n) in time and O(1) in space.

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design