KatInterview

Duplicate Linked List with Arbitrary Pointers

Linked ListsAuto-graded · 20 test cases
MediumAuto-gradedLinked Listslinked-listsarraysdeep-copy

Last updated

Demonstrate deep copying of a sequential structural chain featuring auxiliary target links via node-level or serialized array transformations.

A specialized singly linked list structure encodes node sequence values alongside auxiliary pointers. In addition to a standard sequential next reference connecting node $i$ to node $i+1$, each node contains a random pointer pointing to any node in the structure, or to null.

In the serialized representation:

  • values[i] represents the stored data value of node $i$.
  • random_indices[i] contains the zero-based index of the node targeted by node $i$'s random pointer, or -1 if the pointer is null.

Your task is to implement a function that constructs a complete deep copy of this serialized structure. The returned output must be a two-element list containing brand-new arrays for values and random_indices respectively. The new data structures must fully mirror the content and relational references of the original input without sharing any underlying array references (i.e. mutating the returned structures must not affect the original inputs).

Constraints

  • $0 \le n \le 10^4$, where $n$ is the length of values (and random_indices).
  • $-10^4 \le \text{values}[i] \le 10^4$ for all $0 \le i < n$.
  • $-1 \le \text{random_indices}[i] < n$ for all $0 \le i < n$.
  • The length of values is guaranteed to match the length of random_indices.

Examples

Example 1

Input: duplicate_random_linked_list([1, 2, 3], [2, -1, 0])

Output: [[1, 2, 3], [2, -1, 0]]

Example 2

Input: duplicate_random_linked_list([7], [0])

Output: [[7], [0]]

Example 3

Input: duplicate_random_linked_list([4, 5, 6], [-1, -1, -1])

Output: [[4, 5, 6], [-1, -1, -1]]

Example 4

Input: duplicate_random_linked_list([10, 10, -3, 8], [-1, 0, 3, 1])

Output: [[10, 10, -3, 8], [-1, 0, 3, 1]]

Hints

Hint 1

In a serialized array format, duplicating node data and maintaining target index mappings requires creating independent instances of the input lists.

Hint 2

Notice how relative target positions (indices) remain identical between the source list and its deep copy.

Hint 3

Ensure your function handles edge cases like empty lists, self-referencing nodes, and list elements pointing to null targets (-1).