Random Pick with Blacklist - Problem
You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist.
Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned.
Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.
Implement the Solution class:
Solution(int n, int[] blacklist)Initializes the object with the integernand the blacklisted integersblacklist.int pick()Returns a random integer in the range[0, n - 1]and not inblacklist.
Input & Output
Example 1 — Basic Case
$
Input:
n = 7, blacklist = [2, 3, 5]
›
Output:
Random valid number from {0, 1, 4, 6}
💡 Note:
Valid numbers are 0, 1, 4, 6. Each should be returned with equal probability 1/4.
Example 2 — Small Range
$
Input:
n = 4, blacklist = [1]
›
Output:
Random valid number from {0, 2, 3}
💡 Note:
Only number 1 is blacklisted, so valid choices are 0, 2, 3 with probability 1/3 each.
Example 3 — Empty Blacklist
$
Input:
n = 3, blacklist = []
›
Output:
Random valid number from {0, 1, 2}
💡 Note:
No blacklist means all numbers 0, 1, 2 are valid with equal probability 1/3.
Constraints
- 1 ≤ n ≤ 109
- 0 ≤ blacklist.length ≤ min(105, n - 1)
- 0 ≤ blacklist[i] < n
- All values in blacklist are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
Range [0, n-1] with blacklisted numbers
2
Challenge
Pick random valid number efficiently
3
Output
Random number not in blacklist
Key Takeaway
🎯 Key Insight: Map blacklisted positions to valid tail positions to avoid rejection sampling and achieve O(1) pick time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code