|
| 1 | +# Copy List with Random Pointer |
| 2 | + |
| 3 | +**Difficulty:** Medium |
| 4 | +**Topics:** Hash Table, Linked List |
| 5 | +**Tags:** neetcode-150 |
| 6 | + |
| 7 | +**LeetCode:** [Problem 138](https://leetcode.com/problems/copy-list-with-random-pointer/description/) |
| 8 | + |
| 9 | +## Problem Description |
| 10 | + |
| 11 | +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`. |
| 12 | + |
| 13 | +Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#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**. |
| 14 | + |
| 15 | +Return _the head of the copied linked list_. |
| 16 | + |
| 17 | +The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: |
| 18 | + |
| 19 | +- `val`: an integer representing `Node.val` |
| 20 | +- `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. |
| 21 | + |
| 22 | +## Examples |
| 23 | + |
| 24 | +### Example 1: |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +``` |
| 29 | +Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] |
| 30 | +Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] |
| 31 | +``` |
| 32 | + |
| 33 | +### Example 2: |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | +``` |
| 38 | +Input: head = [[1,1],[2,1]] |
| 39 | +Output: [[1,1],[2,1]] |
| 40 | +``` |
| 41 | + |
| 42 | +### Example 3: |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +``` |
| 47 | +Input: head = [[3,null],[3,0],[3,null]] |
| 48 | +Output: [[3,null],[3,0],[3,null]] |
| 49 | +``` |
| 50 | + |
| 51 | +## Constraints |
| 52 | + |
| 53 | +- 0 <= n <= 1000 |
| 54 | +- -10^4 <= Node.val <= 10^4 |
| 55 | +- Node.random is null or points to some node in the linked list. |
0 commit comments