> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Copy List with Random Pointer Python Solution

> Tested Python solution for LeetCode 138 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 138, Medium. Topics: Hash Table, Linked List. [View on LeetCode](https://leetcode.com/problems/copy-list-with-random-pointer/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 138   # by problem number
lcpy gen -s copy_list_with_random_pointer   # by problem name
```

## 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**](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**.

Return *the head of the copied linked list*.

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:

* `val`: an integer representing `Node.val`
* `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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2019/12/18/e1.png)

```
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
```

![Example 2](https://assets.leetcode.com/uploads/2019/12/18/e2.png)

```
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
```

![Example 3](https://assets.leetcode.com/uploads/2019/12/18/e3.png)

```
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
```

### Constraints

* 0 \<= n \<= 1000
* -10^4 \<= Node.val \<= 10^4
* Node.random is null or points to some node in the linked list.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/copy_list_with_random_pointer/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/copy_list_with_random_pointer/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from __future__ import annotations


class Node:
    def __init__(self, x: int, next: Node | None = None, random: Node | None = None):
        self.val = int(x)
        self.next = next
        self.random = random


class Solution:
    # Time: O(n)
    # Space: O(1) extra (interweaves clones into the original list)
    def copy_random_list(self, head: Node | None) -> Node | None:
        if head is None:
            return None

        # Phase 1: insert each clone right after its original node
        current: Node | None = head
        while current is not None:
            nxt = current.next
            clone = Node(current.val, nxt)
            current.next = clone
            current = nxt

        # Phase 2: wire each clone's random from its original's random
        current = head
        while current is not None:
            clone = current.next
            assert clone is not None
            if current.random is not None:
                rand_clone = current.random.next
                assert rand_clone is not None
                clone.random = rand_clone
            current = clone.next

        # Phase 3: detach clones, restore the original, return the copy head
        current = head
        copy_head = head.next
        while current is not None:
            clone = current.next
            assert clone is not None
            current.next = clone.next
            tail = clone.next
            clone.next = tail.next if tail is not None else None
            current = current.next

        return copy_head
```

## Complexity

| Time | Space                                                  |
| ---- | ------------------------------------------------------ |
| O(n) | O(1) extra (interweaves clones into the original list) |

## Tags

[NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
