PIXELBANKv9.1.0
Menu

Copy List with Random Pointer

Given a linked list where each node has a val and a random pointer (which can point to any node or null), create a deep copy of the list.

Input: Each node as val,random_index separated by semicolons. Random index -1 means null.

Output: Same format showing the deep copy is correct.

Example:

Input:
7,-1;13,0;11,4;10,2;1,0
Output:
7,-1;13,0;11,4;10,2;1,0
Reasoning:
  • The input 7,-1;13,0;11,4;10,2;1,0 represents a linked list where each node has a value and a random pointer index. The random index -1 means the pointer is null.
  • We create a deep copy of the list by iterating over each node and assigning a new node with the same val. The random pointer of each new node is updated based on the original node's random index.
  • For the given input, the original list has nodes with values 7, 13, 11, 10, and 1. The random pointers are updated as follows:
    • Node 13 points to node 7 (index 0),
    • Node 11 points to node 1 (index 4),
    • Node 10 points to node 13 (index 2).
  • The resulting deep copy has the same node values and random pointer indices, resulting in the output 7,-1;13,0;11,4;10,2;1,0.

Constraints:

  • 0 <= n <= 1000
  • -10^4 <= Node.val <= 10^4
  • random_index is -1 or a valid index
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.