FastPrepCopy a Doubly Linked List with a Special Pointer

Copy a Doubly Linked List with a Special Pointer

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A doubly linked list has one node per row of nodes. Row i is [value, specialIndex]:

  • The node's left pointer targets row i - 1, or is null for the first row.
  • The node's right pointer targets row i + 1, or is null for the final row.
  • specialIndex is the row targeted by the node's arbitrary special pointer, or -1 for 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 newValue fit a signed 32-bit integer.
  • Every stored special index and newSpecialIndex is -1 or a valid row index.
  • 0 <= mutationIndex < nodes.length.
  • The returned deep-copy snapshot must retain every pre-mutation value and special link.

More Microsoft problems

See Microsoft hiring insights
public int[][][] copyDoublyListWithSpecialPointer(int[][] nodes, int mutationIndex, int newValue, int newSpecialIndex) {
    // Write your code here.
}
nodes[[7,2],[13,-1],[11,0]]
mutationIndex1
newValue99
newSpecialIndex2
expected[[[7,2],[99,2],[11,0]],[[7,2],[13,-1],[11,0]]]
Checking account…