Description

Given an array with possible duplicates, implement a class that returns a random index of the given target number. Each valid index has equal probability.

Examples

Input:nums = [1,2,3,3,3], target = 3
Output:2, 3, or 4 with equal probability
Explanation:

Reservoir sampling.

Input:nums = [1], target = 3
Output:2, 3, or 4 with equal probability
Explanation:

Edge case with a single-element array.

Input:nums = [5,7,5,4,3], target = 5
Output:0 or 2 with equal probability
Explanation:

The target value 5 appears at indices 0 and 2. Since the task requires pick randomly with equal probability, each valid index has a 50% chance of being selected.

Constraints

  • 1 ≤ nums.length ≤ 2 * 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!