Copy List Nodes with Next and Arbitrary Random Links

Quick Overview

Deep-copy a random-pointer list with identity-based counterpart mapping and no links into the original nodes.

Copy List Nodes with Next and Arbitrary Random Links

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Deep-copy a linked list whose nodes contain `val`, `next`, and `random`. A random link can point to any node in the list, including itself, or to null. Return the new head. Create exactly one new node per original node and preserve both kinds of links through the corresponding new nodes. No pointer in the copy may refer to an original node. ```cpp Node* copyRandomList(Node* head); ``` The function receives only the original custom-node head. Display pairs `[value,randomIndex]` use zero-based indices along the next chain; they are not array arguments. ### Examples ```text Original display: [[5,1],[5,0]] Copy display: [[5,1],[5,0]] ``` The equal-valued nodes are distinct, and the new random links point to their new counterparts. ```text Original display: [[-2,0]] Copy display: [[-2,0]] ``` ### Constraints - There are between 0 and 1000 nodes. - Values lie between -10000 and 10000, inclusive. - Every random pointer is null or refers to a node in the original list.

Overview: Deep-copy a random-pointer list with identity-based counterpart mapping and no links into the original nodes.

Amazon logo
Amazon
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Deep-copy a linked list whose nodes contain val, next, and random. A random link can point to any node in the list, including itself, or to null. Return the new head. Create exactly one new node per original node and preserve both kinds of links through the corresponding new nodes. No pointer in the copy may refer to an original node.

Node* copyRandomList(Node* head);

The function receives only the original custom-node head. Display pairs [value,randomIndex] use zero-based indices along the next chain; they are not array arguments.

Examples

Original display: [[5,1],[5,0]]
Copy display:     [[5,1],[5,0]]

The equal-valued nodes are distinct, and the new random links point to their new counterparts.

Original display: [[-2,0]]
Copy display:     [[-2,0]]

Constraints

  • There are between 0 and 1000 nodes.
  • Values lie between -10000 and 10000, inclusive.
  • Every random pointer is null or refers to a node in the original list.