MediumNo. 0398
Random Pick Index — LeetCode 398 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Reservoir Sampling, Hash Table, Math, Randomized
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0519 | Random Flip Matrix | Medium |
| 0380 | Insert Delete GetRandom O(1) | Medium |
| 0381 | Insert Delete GetRandom O(1) - Duplicates allowed | Hard |
| 0710 | Random Pick with Blacklist | Hard |
| 0391 | Perfect Rectangle | Hard |
| 0012 | Integer to Roman | Medium |
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.