LeetCode 398: Random Pick Index Solution

Master LeetCode problem 398 (Random Pick Index), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

398. Random Pick Index

Problem Explanation

Explanation

To solve this problem, we can use a hashmap to store the indices of each target number in the input array. When we need to pick a random index for a given target, we can simply retrieve the list of indices for that target and select a random index from that list.

Algorithm

  1. Initialize a hashmap to store target numbers as keys and a list of their corresponding indices as values.
  2. Iterate through the input array and populate the hashmap.
  3. When picking a random index for a target, retrieve the list of indices from the hashmap and return a random index from that list.

Time Complexity

  • Initialization: O(n) where n is the length of the input array.
  • Pick: O(1) on average.

Space Complexity

  • O(n) where n is the length of the input array.

Solution Code

import java.util.*;

class Solution {
    Map<Integer, List<Integer>> indexMap;

    public Solution(int[] nums) {
        indexMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            indexMap.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
        }
    }

    public int pick(int target) {
        List<Integer> indices = indexMap.get(target);
        int randomIndex = (int) (Math.random() * indices.size());
        return indices.get(randomIndex);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 398 (Random Pick Index)?

This page provides optimized solutions for LeetCode problem 398 (Random Pick Index) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 398 (Random Pick Index)?

The time complexity for LeetCode 398 (Random Pick Index) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 398 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 398 in Java, C++, or Python.

Back to LeetCode Solutions