Copy a Doubly Linked List with a Special Pointer
Problem statement
A doubly linked list has one node per row of nodes. Row i is [value, specialIndex]:
- The node's
leftpointer targets rowi - 1, or is null for the first row. - The node's
rightpointer targets rowi + 1, or is null for the final row. specialIndexis the row targeted by the node's arbitraryspecialpointer, or-1for null.
Build the list and create a deep copy. Every copied left, right, and special pointer must target only copied nodes.
After copying, mutate the original node at mutationIndex: set its value to newValue and redirect its special pointer to newSpecialIndex, where -1 means null. Return two encoded snapshots in order: the mutated original list, then the unchanged deep copy.
Function
copyDoublyListWithSpecialPointer(nodes: int[][], mutationIndex: int, newValue: int, newSpecialIndex: int) → int[][][]Examples
Example 1
nodes = [[7,2],[13,-1],[11,0]]mutationIndex = 1newValue = 99newSpecialIndex = 2return = [[[7,2],[99,2],[11,0]],[[7,2],[13,-1],[11,0]]]The middle original node changes to [99,2]. The copied middle node remains [13,-1], proving that the copy is independent.
Example 2
nodes = [[5,0]]mutationIndex = 0newValue = 8newSpecialIndex = -1return = [[[8,-1]],[[5,0]]]The original loses its self-reference, while the copied node keeps its value and a special pointer to itself.
Example 3
nodes = [[1,3],[2,0],[3,1],[4,2]]mutationIndex = 2newValue = 30newSpecialIndex = 3return = [[[1,3],[2,0],[30,3],[4,2]],[[1,3],[2,0],[3,1],[4,2]]]The special pointers form a cycle. The mutation changes only the original third node; the cloned cycle stays unchanged.
Constraints
1 <= nodes.length <= 50000.- Every row contains exactly
[value, specialIndex]. - All node values and
newValuefit a signed 32-bit integer. - Every stored special index and
newSpecialIndexis-1or a valid row index. 0 <= mutationIndex < nodes.length.- The returned deep-copy snapshot must retain every pre-mutation value and special link.