MEDIUM NC#39 Linked List

138. Copy List with Random Pointer

๐Ÿ“– Problem

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. Return the head of the copied linked list.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use two passes: first to create all node copies, second to set pointers
  • โ†’ Use hash map to map original nodes to their copies
  • โ†’ In first pass, create all nodes and map them
  • โ†’ In second pass, set next and random pointers using the map
  • โ†’ Time: O(n), Space: O(n)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse two passes: first to create all node copies, second to set pointers
  • โ€ขUse hash map to map original nodes to their copies
  • โ€ขIn first pass, create all nodes and map them

Common Pitfalls

  • โ€ขIn second pass, set next and random pointers using the map
  • โ€ขTime: O(n), Space: O(n)

๐Ÿงช Test Cases

Test Case 1
Not run
Input:
_copyRandomList(head: Node | null);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit