KatInterview

Clone a Linked Chain with Arbitrary Jump Links

Linked ListsAuto-graded · 18 test cases
MediumAuto-gradedLinked Listslinked-listhash-mapdeep-copy

Last 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 position i (0-based).
  • random_indices[i] is either None (the node's random pointer is empty) or an integer j with 0 <= j < n (the node's random pointer references the node at position j).

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:

  • val is the node's value, and
  • r is the 0-based position, within the copy, of the node that its random pointer references, or None if 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, and len(values) == len(random_indices).
  • Each values[i] is an integer.
  • Each random_indices[i] is None or 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.