Skip to content
Decoder

Copy List with Random Pointer

Medium

Problem

Each node of this linked list has a val, a next pointer, and an extra random pointer that can point to any node in the list, or to nothing. Return a deep copy: a brand-new list of new nodes with the same values, where every copied next and random points to the matching copied node. No pointer in the copy may point back into the original list.

The Node class is defined in the starter (the harness only knows ListNode). Below, each node is written as [val, index of random node].

Example 1

Input
[[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
Output
a new list with the same shape

Example 2

Input
[[1, 0]]
Output
one node whose random is itself

Example 3

Input
[]
Output
None

Constraints

  • 0 <= number of nodes <= 1000
  • -10^4 <= Node.val <= 10^4
  • Node.random is empty or points to a node in the list.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.