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 integern
and the blacklisted integersblacklist
.int pick()
Returns a random integer in the range[0, n - 1]
and not inblacklist
.
Example 1:
Input
["Solution", "pick", "pick", "pick", "pick", "pick", "pick", "pick"]
[[7, [2, 3, 5]], [], [], [], [], [], [], []]
Output
[null, 0, 4, 1, 6, 1, 0, 4]
Explanation
Solution solution = new Solution(7, [2, 3, 5]);
solution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,
// 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).
solution.pick(); // return 4
solution.pick(); // return 1
solution.pick(); // return 6
solution.pick(); // return 1
solution.pick(); // return 0
solution.pick(); // return 4
Constraints:
1 <= n <= 10^9
0 <= blacklist.length <= min(10^5, n - 1)
0 <= blacklist[i] < n
All the values of
blacklist
are unique.At most
2 * 10^4
calls will be made topick
.
Solution
class Solution {
int M; //M is the number of integers from [0, N) which not in blacklist
Random r;
HashMap<Integer, Integer> map;
public Solution(int N, int[] blacklist) {
map = new HashMap<>();
r = new Random();
for (int b: blacklist) {
map.put(b, -1);
}
M = N - map.size();
for (int b: blacklist) {
if (b < M) {
while (map.containsKey(N - 1)) {
N--;
}
map.put(b, N - 1);//remaping b to N-1, so the key will be the element in blacklist, and the value will be the number it remapping. so each time we choose a one, we check if we need to remapping, if we need to remaping, then we do it. if it is not, then we use it.
//this mechanism actually avoid that possiblity discard the random number rach time, it is genius
N--;
}
}
}
public int pick() {
int p = r.nextInt(M); //choose any integer from [0, M)
if (map.containsKey(p)) { //if p is contained in map, then remapping it
return map.get(p);
}
return p;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n, blacklist);
* int param_1 = obj.pick();
*/
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).