We want to randomly pick an index for a number thats in a list of numbers.
To do this, we can populate a dict of num → list and then choice on that list. This solution does that.
class Solution:
def __init__(self, nums: List[int]):
m = defaultdict(list)
for i, n in enumerate(nums):
m[n].append(i)
self.nums = m
def pick(self, target: int) -> int:
return choice(self.nums[target])