KatInterview

398. Random Pick Index

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a class that can, given a target number, randomly pick one of its indices from an array that may contain duplicates. Each index of the target number must have an equal probability of being chosen. The pick method can be called multiple times for different targets.

Solution

Random Pick Index in Python

import random
from collections import defaultdict

class Solution:

    def __init__(self, nums: List[int]):
        # Use a defaultdict to simplify appending to lists. When a key is accessed
        # for the first time, it is initialized with an empty list.
        self.indices_map = defaultdict(list)
        # Iterate through the input array with indices.
        for i, num in enumerate(nums):
            self.indices_map[num].append(i)

    def pick(self, target: int) -> int:
        # Get the list of indices for the target.
        # The problem guarantees that the target exists.
        indices = self.indices_map[target]
        # random.choice is a convenient and efficient way to pick a random element from a non-empty sequence.
        return random.choice(indices)


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

Random Pick Index in Java

class Solution {
    // A map to store the indices of each number.
    // Key: number from nums, Value: a list of indices where this number appears.
    private Map<Integer, List<Integer>> indicesMap;
    private Random rand;

    public Solution(int[] nums) {
        this.indicesMap = new HashMap<>();
        this.rand = new Random();
        // Pre-process the array to store indices for each number.
        for (int i = 0; i < nums.length; i++) {
            // If the number is not yet a key in the map, create a new list.
            // this.indicesMap.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
            // The above lambda can be written more verbosely as:
            if (!this.indicesMap.containsKey(nums[i])) {
                this.indicesMap.put(nums[i], new ArrayList<>());
            }
            // Add the current index to the list for this number.
            this.indicesMap.get(nums[i]).add(i);
        }
    }
    
    public int pick(int target) {
        // Get the list of indices for the target.
        // The problem guarantees that the target exists in the array.
        List<Integer> indices = this.indicesMap.get(target);
        // Generate a random index within the bounds of the list's size (0 to size-1).
        int randomIndex = this.rand.nextInt(indices.size());
        // Return the original index stored at the randomly chosen position in the list.
        return indices.get(randomIndex);
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */

Random Pick Index in C++

class Solution {
private:
    // A hash map to store the indices of each number.
    // Key: number from nums, Value: a vector of indices where this number appears.
    unordered_map<int, vector<int>> indices_map;

public:
    Solution(vector<int>& nums) {
        // Seed the random number generator. In a real application, you might do this
        // globally, but for LeetCode, placing it in the constructor is fine.
        srand(time(0));
        
        // Iterate through the input array to populate the hash map.
        for (int i = 0; i < nums.size(); ++i) {
            indices_map[nums[i]].push_back(i);
        }
    }
    
    int pick(int target) {
        // Retrieve the vector of indices for the given target.
        // The problem guarantees that the target exists.
        vector<int>& indices = indices_map[target];
        
        // Generate a random number between 0 and size-1.
        // rand() % N is a common way to get a random number in a range on competitive programming platforms.
        int randomIndex = rand() % indices.size();
        
        // Return the element at the random index.
        return indices[randomIndex];
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(nums);
 * int param_1 = obj->pick(target);
 */

Random Pick Index in TypeScript

class Solution {
    private indicesMap: Map<number, number[]>;

    constructor(nums: number[]) {
        this.indicesMap = new Map<number, number[]>();
        // Pre-process the array to populate the map.
        for (let i = 0; i < nums.length; i++) {
            const num = nums[i];
            // If the number is not in the map, initialize its index list.
            if (!this.indicesMap.has(num)) {
                this.indicesMap.set(num, []);
            }
            // Add the current index to the list for this number.
            // The '!' non-null assertion tells TypeScript that we know this value is not undefined.
            this.indicesMap.get(num)!.push(i);
        }
    }

    pick(target: number): number {
        // Get the list of indices for the target.
        // The '!' non-null assertion is safe because the problem guarantees the target exists.
        const indices = this.indicesMap.get(target)!;
        // Calculate a random index within the bounds of the indices array (0 to length-1).
        const randomIndex = Math.floor(Math.random() * indices.length);
        // Return the original index.
        return indices[randomIndex];
    }
}

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

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.