Random Pick Index — LeetCode 398 Python Solution
MediumReservoir SamplingHash TableMathRandomized
- Problem
- #398
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["Solution", "pick", "pick", "pick"]
- Output
- [null, 4, 0, 2]
- Explanation
- Solution solution = new Solution([1, 2, 3, 3, 3]);
Python solution
Python
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
n = ans = 0
for i, v in enumerate(self.nums):
if v == target:
n += 1
x = random.randint(1, n)
if x == n:
ans = i
return ans
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 398. Random Pick Index is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 398. Random Pick Index?
- LeetCode 398. Random Pick Index is rated Medium on LeetCode.
- What is the time complexity of LeetCode 398. Random Pick Index?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 398. Random Pick Index?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 398. Random Pick Index cover?
- LeetCode 398. Random Pick Index is tagged Reservoir Sampling, Hash Table, Math and Randomized on LeetCode.