<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p>

<p>Implement the <code>Solution</code> class:</p>

<ul>
	<li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li>
	<li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i&#39;s, then each index should have an equal probability of returning.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input</strong>
[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]
[[[1, 2, 3, 3, 3]], [3], [1], [3]]
<strong>Output</strong>
[null, 4, 0, 2]

<strong>Explanation</strong>
Solution solution = new Solution([1, 2, 3, 3, 3]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
	<li><code>target</code> is an integer from <code>nums</code>.</li>
	<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>
</ul>

import random
class Solution:


    # def __init__(self, nums: List[int]):
    #     self.hm = {}
    #     for i, num in enumerate(nums):
    #         if num not in self.hm:
    #             self.hm[num] = []
    #         self.hm[num].append(i)


    # def pick(self, target: int) -> int:
        
    #     idxs = self.hm.get(target)

    #     return idxs[random.randint(0, len(idxs)-1)] if idxs else 0
        

    def __init__(self, nums: List[int]):
        # save nums array for reservoir sampling for the first
        # call to pick
        self.nums = nums
        # save lists of indices to skip reservoir sampling
        # after we've done one pick
        self.indices = defaultdict(list)

    def pick(self, target: int) -> int:
    # Check if the target has already been picked before.
    # If yes, retrieve a random index from the cached list.
        if target in self.indices:
            return self.indices[target][
                randint(0, len(self.indices[target])-1)
            ]
        
        # If target has not been picked before, perform reservoir sampling
        r = None  # Variable to store the randomly selected index
        count = 0  # Counter to keep track of occurrences of the target

        # Iterate through the entire list to find the target and perform sampling
        for i, n in enumerate(self.nums):
            if n == target:
                # Reservoir sampling logic:
                # If this is the first occurrence or the random choice is valid,
                # update the result index to the current index.
                # if r is None or randint(0, count) == 0:
                #     r = i
                # count += 1  # Increment the count of occurrences of the target
                count += 1
                if random.random() < 1 / count:
                    r = i

            # Add the current index to the list of indices for the current value
            self.indices[n].append(i)
        
        # Return the randomly selected index of the target
        return r

24200