> ## 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.

# Linked List Random Node Python Solution

> Tested Python solution for LeetCode 382 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 382, [Medium](/catalog/medium). Topics: [Linked List](/catalog/topics/linked-list), [Math](/catalog/topics/math), Reservoir Sampling, Randomized. [View on LeetCode](https://leetcode.com/problems/linked-list-random-node/description/).

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

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

## Problem

Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.

Implement the `Solution` class:

* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg)

```
Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]

Explanation
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
```

```
Input
["Solution", "getRandom", "getRandom"]
[[[7]], [], []]
Output
[null, 7, 7]

Explanation
Solution solution = new Solution([7]);
solution.getRandom(); // return 7, the only node in the list.
```

### Constraints

* The number of nodes in the linked list will be in the range `[1, 10^4]`.
* `-10^4 <= Node.val <= 10^4`
* At most `10^4` calls will be made to `getRandom`.

**Follow up:**

* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import random

from leetcode_py import ListNode


class Solution:
    # Time: init O(1), get_random O(n)
    # Space: O(1)
    def __init__(self, head: ListNode[int] | None) -> None:
        self.head = head

    def get_random(self) -> int:
        node = self.head
        assert node is not None
        reservoir = node.val
        current = node.next
        seen = 2
        while current is not None:
            if random.randint(1, seen) == 1:
                reservoir = current.val
            current = current.next
            seen += 1
        return reservoir
```

## Complexity

| Time | Space |
| - | - |
| init O(1), get\_random O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.