InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Copy List with Random Pointer

medium Original ↗ 00:00

Problem

You are given a linked list where each node has a next pointer and a random pointer. The random pointer may point to any node in the list, or to None.

Return a deep copy of the list. The copy must contain the same number of new nodes with the same values, and its next and random pointers must reproduce the structure of the original list. No pointer in the copy may reference a node in the original list, and no pointer in the original may reference a node in the copy.

Examples

Notation: [val, random_index] where random_index is the position of the node the random pointer targets (or null).

  • Input: [[7,null],[13,0],[11,4],[10,2],[1,0]] → Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] The copy is five new nodes with the same structure; the copy of 13 has its random pointing at the copy of 7.
  • Input: [[1,1],[2,1]] → Output: [[1,1],[2,1]] Both random pointers point at the second node, including the second node pointing at itself.
  • Input: [[3,null],[3,0],[3,null]] → Output: [[3,null],[3,0],[3,null]] Duplicate values are allowed; node identity, not value, determines the structure to copy.

Constraints

  • Number of nodes is in [0, 1000].
  • -10^4 <= Node.val <= 10^4
  • random is None or points at a node of the same list.

Think about it first

Hint 1 Copying val and next is a single walk down the list. The hard part is random: when you copy a node, the node its random points at may not have been copied yet. How do you translate "original node X" into "copy of X"?
Hint 2 A dictionary mapping original node → its clone answers that translation in O(1). Two passes: first create all clones, then wire every clone's next and random through the map.
Hint 3 To do it with O(1) extra space: splice each clone right after its original (A -> A' -> B -> B' -> ...). Then original.random.next is the clone's random target. A third pass unzips the two lists.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug