[LeetCode] Random Pick with Blacklist

710. Random Pick with Blacklist

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int n;
vector<int> blacklist;
unordered_map<int, int> cache;
public:
Solution(int n, vector<int>& b) {
this->n = n - b.size();
sort(b.begin(), b.end());
this->blacklist = b;
}

int pick() {
int pi = rand() % n;
int key = pi;
if(cache.count(key)) return cache[key];
auto it = upper_bound(blacklist.begin(), blacklist.end(), pi);
int diff = it - blacklist.begin();
while(diff) {
pi += diff;
auto nit = upper_bound(it, blacklist.end(), pi);
diff = nit - it;
it = nit;
}
return cache[key] = pi;
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(n, blacklist);
* int param_1 = obj->pick();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/24/PS/LeetCode/random-pick-with-blacklist/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.