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

# Random Pick Index Python Solution with Tests

> Tested Python solution for LeetCode 398 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 398, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Math](/catalog/topics/math), Reservoir Sampling, Randomized. [View on LeetCode](https://leetcode.com/problems/random-pick-index/description/).

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

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

## Problem

Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.

Implement the `Solution` class:

* `Solution(int[] nums)` Initializes the object with the array `nums`.
* `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid `i`'s, then each index should have an equal probability of returning.

### Examples

```
Input
["Solution", "pick", "pick", "pick"]
[[[1, 2, 3, 3, 3]], [3], [1], [3]]
Output
[null, 4, 0, 2]

Explanation
Solution solution = new Solution([1, 2, 3, 3, 3]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
```

### Constraints

* `1 <= nums.length <= 2 * 10^4`
* `-2^31 <= nums[i] <= 2^31 - 1`
* `target` is an integer from `nums`.
* At most `10^4` calls will be made to `pick`.

**Follow up:** What is the time and space complexity of your solution? Could you do it with `O(1)` extra space?

## Solution

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

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


class Solution:
    # Time: O(n) init, O(1) pick
    # Space: O(n)
    def __init__(self, nums: list[int]) -> None:
        self.indices: dict[int, list[int]] = defaultdict(list)
        for i, num in enumerate(nums):
            self.indices[num].append(i)

    def pick(self, target: int) -> int:
        return random.choice(self.indices[target])
```

## Complexity

| Time | Space |
| - | - |
| O(n) init, O(1) pick | O(n) |

## Tags


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