AlgoMaster Logo

Copy List with Random Pointer

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. HashMap

Intuition:

The main idea is to traverse the original linked list and copy each node. During this traversal, a HashMap is used to keep track of the original nodes and their corresponding copied nodes. By using this map, we can access the copied node of a particular original node efficiently.

The algorithm can be summarized in two main passes over the linked list:

  1. Copy Nodes and Fill HashMap:
    • Create a new list node for each node in the original list,
    • Save the mapping between the original node and copied node in a HashMap.
  2. Assign Next and Random Pointers:
    • Iterate over the original list again. For each node, set the next and random pointers for the copied nodes using the HashMap.

Code:

2. Interleaved List

Intuition:

We can optimize the space used for storing node mappings by integrating the copied nodes directly into the original list. The procedure is as follows:

  1. First pass: For each node in the original list, create a new node and interleaved it between the current node and the next node.
  2. Second pass: Assign random pointers for the newly created nodes by utilizing the existing random pointers.
  3. Third pass: Separate the original and copied list.

This approach removes the need for a HashMap to store node mappings, thereby reducing the space complexity.

Code: