Skip to contentKEEP THE CRAFTTHE SANCTUARY

Copy a Random-Pointer List

Deep-copy a list whose nodes also point at a random node, using a list of [value, random] records.

The problem

Implement Solution.copyRandomList(records). The input describes a linked list in which every node has a next pointer and a random pointer. Node i is written as the record [value, random_index]: its next node is node i + 1, and random_index is the position of the node its random pointer points to, or None if it points nowhere. For example, [[7, None], [13, 0]] means node 0 holds 7 with no random link, and node 1 holds 13 with its random pointer on node 0. Return a deep copy in the same format: a new outer list with a new [value, random_index] list for every node, describing the same values and links. Do not return or reuse the input lists. There are at most 1,000 nodes, and values are between -10,000 and 10,000.

Starter code

class Solution:
    def copyRandomList(self, records):
        pass

Public examples

  1. records = [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]gives[[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]
  2. records = [[5, 1], [8, 0]]gives[[5, 1], [8, 0]]
  3. records = [[-4, None], [0, None]]gives[[-4, None], [0, None]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.