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
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)
๐งญ Prerequisites
๐ ๏ธ 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
_copyRandomList(head: Node | null); Computed from hidden reference ๐ Code Editor
๐ค Output