Clone a Linked Chain with Arbitrary Jump Links
Linked ListsAuto-graded · 18 test casesLast updated
Build a singly linked list with extra jump pointers from index arrays, deep-copy it without sharing nodes, and report the copy's structure by index.
Clone a Linked Chain with Arbitrary Jump Links
A singly linked list has nodes that each store an integer val, a next pointer, and a second pointer called random. The random pointer may reference any node in the list (including the node itself, an earlier node, or a later node), or it may be empty (None).
The list is described by two arrays of equal length n:
values[i]is the value of the node at positioni(0-based).random_indices[i]is eitherNone(the node'srandompointer is empty) or an integerjwith0 <= j < n(the node'srandompointer references the node at positionj).
The next pointer of position i references position i + 1, and the last node's next is None.
Task
Build the list described by the arrays, then create a deep copy of it. The copy must consist entirely of new nodes: every next and random pointer in the copy must reference nodes of the copy, never nodes of the original. The original list must remain unchanged.
Finally, describe the copy by walking it from its head along next pointers. For each node in that order, output a pair [val, r], where:
valis the node's value, andris the 0-based position, within the copy, of the node that itsrandompointer references, orNoneif the pointer is empty.
Return the list of these pairs. For an empty input, return an empty list.
Values may repeat, so a node cannot be identified by its value. Several random pointers may target the same node.
Constraints
0 <= n <= 10^5, andlen(values) == len(random_indices).- Each
values[i]is an integer. - Each
random_indices[i]isNoneor an integer in[0, n - 1]. - Use an iterative approach; recursion depth could otherwise be a problem for long lists.
Examples
Example 1
Input: clone_random_chain([], [])
Output: []
Example 2
Input: clone_random_chain([7, 13, 11], [None, 0, 2])
Output: [[7, None], [13, 0], [11, 2]]
Example 3
Input: clone_random_chain([1, 1, 2, 3], [3, None, 1, 0])
Output: [[1, 3], [1, None], [2, 1], [3, 0]]
Hints
Hint 1
A random pointer may target a node that has not been copied yet, so you need a reliable way to find the copy of any original node.
Hint 2
Do two passes: first create one new node for every original node and remember which copy belongs to which original (by node identity, not by value). Then wire next and random in a second pass.
Hint 3
To report positions, walk the copy once and record each node's index by identity; then convert each random pointer to its recorded index, using None for empty pointers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The difficulty in copying is that a random pointer can target a node that has not been copied yet. The fix is to separate creating nodes from wiring them.
- Pass 1: Walk the original list and create one new node per original node. Store them in a dictionary keyed by the original node object (identity, not value, since values can repeat).
- Pass 2: Walk the original list again. For each original node, look up its clone and set
clone.next = mapping[node.next]andclone.random = mapping[node.random]. A missing target (None) maps toNone. - Report: Walk the copy from its head, assigning each node its position. Then emit
[val, position of random target or None]for each node.
The function also first builds the original list from the two index arrays, with next linking position i to i + 1 and random linking to nodes[random_indices[i]].
Why it is correct
After pass 1 every original node has exactly one clone, so every pointer target has a counterpart regardless of whether it points forward, backward, to itself, or is shared with other nodes. Pass 2 only ever points clone pointers at other clones, so the copy shares no node with the original, and the original is never modified. Positions are computed by node identity, so repeated values cause no ambiguity.
Complexity
- Time: O(n), a constant number of linear passes.
- Space: O(n) for the dictionary and the new nodes. (A constant-extra-space variant interleaves each clone right after its original, sets random pointers via
orig.random.next, then separates the two lists again, but it temporarily modifies the original.)
All loops are iterative, so there is no recursion-depth risk.
Reference solution
from typing import List, Optional
class Node:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
def _copy_list(head):
if head is None:
return None
mapping = {}
cur = head
while cur is not None:
mapping[cur] = Node(cur.val)
cur = cur.next
cur = head
while cur is not None:
clone = mapping[cur]
clone.next = mapping.get(cur.next)
clone.random = mapping.get(cur.random)
cur = cur.next
return mapping[head]
def clone_random_chain(values: List[int], random_indices: List[Optional[int]]) -> List[List[Optional[int]]]:
n = len(values)
nodes = [Node(v) for v in values]
for i in range(n):
if i + 1 < n:
nodes[i].next = nodes[i + 1]
r = random_indices[i]
if r is not None:
nodes[i].random = nodes[r]
head = nodes[0] if nodes else None
copy_head = _copy_list(head)
order = []
position = {}
cur = copy_head
while cur is not None:
position[id(cur)] = len(order)
order.append(cur)
cur = cur.next
result = []
for node in order:
r = None if node.random is None else position[id(node.random)]
result.append([node.val, r])
return result