random_pick_index

 1from collections import defaultdict
 2from random import choice
 3
 4
 5# @leet start
 6class Solution:
 7    """
 8    This question asks us to randomly output the index of a given target number,
 9    where the class has been initialized with an array that may have duplicates.
10
11    To do this, we can iterate through the numbers and generate a mapping of
12    number -> [indexes]. Once we do that, in the pick call, we fetch the indexes
13    that match target and return one of those indexes (using random.choice).
14    """
15
16    def __init__(self, nums: list[int]):
17        self.indexes = defaultdict(list)
18        for i, num in enumerate(nums):
19            self.indexes[num].append(i)
20
21    def pick(self, target: int) -> int:
22        indexes = self.indexes[target]
23        return choice(indexes)
24
25
26# Your Solution object will be instantiated and called as such:
27# obj = Solution(nums)
28# param_1 = obj.pick(target)
29# @leet end
30
31
32def test():
33    assert 2 + 2 == 4
class Solution:
 7class Solution:
 8    """
 9    This question asks us to randomly output the index of a given target number,
10    where the class has been initialized with an array that may have duplicates.
11
12    To do this, we can iterate through the numbers and generate a mapping of
13    number -> [indexes]. Once we do that, in the pick call, we fetch the indexes
14    that match target and return one of those indexes (using random.choice).
15    """
16
17    def __init__(self, nums: list[int]):
18        self.indexes = defaultdict(list)
19        for i, num in enumerate(nums):
20            self.indexes[num].append(i)
21
22    def pick(self, target: int) -> int:
23        indexes = self.indexes[target]
24        return choice(indexes)

This question asks us to randomly output the index of a given target number, where the class has been initialized with an array that may have duplicates.

To do this, we can iterate through the numbers and generate a mapping of number -> [indexes]. Once we do that, in the pick call, we fetch the indexes that match target and return one of those indexes (using random.choice).

Solution(nums: list[int])
17    def __init__(self, nums: list[int]):
18        self.indexes = defaultdict(list)
19        for i, num in enumerate(nums):
20            self.indexes[num].append(i)
indexes
def pick(self, target: int) -> int:
22    def pick(self, target: int) -> int:
23        indexes = self.indexes[target]
24        return choice(indexes)
def test():
33def test():
34    assert 2 + 2 == 4