Leetcode 398: Random Pick Index

grid47
grid47
Exploring patterns and algorithms
Sep 28, 2024 5 min read

A series of indices being selected randomly, with each chosen index softly glowing.
Solution to LeetCode 398: Random Pick Index Problem

Given an integer array nums with potential duplicates, you need to randomly select an index i where nums[i] == target. If there are multiple indices with the same value, the selection should be made with equal probability for each valid index.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of integers `nums` and a target integer. The target integer is guaranteed to exist in the array.
Example: Input: [4, 3, 2, 3, 5], target: 3
Constraints:
• 1 <= nums.length <= 2 * 10^4
• -2^31 <= nums[i] <= 2^31 - 1
• At most 10^4 calls will be made to `pick`.
Output: The output is an integer representing the randomly selected index where `nums[i] == target`. If there are multiple indices with the same value, the selection should be random.
Example: Output: 3
Constraints:
• The function must return an index where `nums[i] == target`.
Goal: The goal is to select a random index where the value matches the target. If there are multiple valid indices, ensure equal probability for all of them.
Steps:
• Store the indices of all occurrences of each number in the array.
• When `pick(target)` is called, randomly select an index from the stored list of indices for that number.
Goal: The solution must handle the array sizes and multiple calls efficiently.
Steps:
• The solution must handle input arrays of length up to 2 * 10^4.
• There will be at most 10^4 calls to the `pick` method.
Assumptions:
• The array `nums` will contain at least one occurrence of the target number when `pick(target)` is called.
Input: Input: [4, 3, 2, 3, 5], target: 3
Explanation: In this case, there are two occurrences of the number 3 (at indices 1 and 3), and the function `pick(3)` can randomly return either 1 or 3 with equal probability.

Input: Input: [1, 1, 2, 2, 3, 3], target: 2
Explanation: There are two occurrences of the number 2 (at indices 2 and 3), and the function `pick(2)` can randomly return either 2 or 3 with equal probability.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus