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 integer n and the blacklisted integers blacklist.
  • int pick() Returns a random integer in the range [0, n - 1] and not in blacklist.

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
Random Pick with Blacklistn = 7, blacklist = [2, 3, 5]Full Range [0, 6]0123456✓ Valid✓ Valid✗ Blocked✗ Blocked✓ Valid✗ Blocked✓ ValidGoal: Randomly pick from {0, 1, 4, 6} with equal probabilitypick() → 4 (random valid number)Each valid number has 1/4 = 25% probability
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
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen