Random Pick Index

Problem Id: 398 Difficulty: Medium


Intuition

Solution


class Solution:
    def __init__(self, nums: List[int]):
        self.indexes = {}
        for index, num in enumerate(nums):
            if num not in self.indexes:
                self.indexes[num] = []
            self.indexes[num].append(index)

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


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)