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 Blacklist INPUT Range [0, n-1] where n = 7 0 1 2 3 4 5 6 Valid Blacklist n = 7 blacklist = [2, 3, 5] whitelist size = 4 Valid Numbers (Whitelist) 0 1 4 6 ALGORITHM STEPS 1 Calculate Whitelist Size m = n - len(blacklist) = 4 2 Create Virtual Mapping Map blacklist in [0,m) to valid numbers in [m,n) Mapping Table: 2 --> 4 3 --> 6 (5 is outside [0,4) so not mapped) 3 Random in [0, m) Pick random r in [0, 4) 4 Return Result If r in map: return map[r] Else: return r FINAL RESULT Virtual Whitelist Array Index: 0 1 2 3 Value: 0 1 4 6 Example Calls: r=0: return 0 (not in map) r=1: return 1 (not in map) r=2: return 4 (mapped!) r=3: return 6 (mapped!) Output: {0, 1, 4, 6} Key Insight: Instead of storing all valid numbers, map blacklisted indices in [0, m) to valid numbers in [m, n). This allows O(1) random pick with only one call to random(), achieving O(B) space where B = blacklist size. TutorialsPoint - Random Pick with Blacklist | Virtual Whitelist Mapping Approach
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