Data Structures19 sections · 729 units
Open in Course

Problem - Copy List with Random

Deep copy with random pointers

A linked list has nodes with an additional random pointer that can point to any node in the list or null. Create a deep copy of this list.

Example: Node 1's random points to node 3, node 2's random points to node 1. Your copy must have the same structure with new nodes.

The challenge: when copying node AA, you might need to set its random pointer to node BB, but BB might not be copied yet.

Two approaches: O(n)O(n) space with a hash map, or O(1)O(1) space with interleaving. Constraints: up to 10001000 nodes, values from 104-10^4 to 10410^4.