Skip to content

Latest commit

 

History

History

710

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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.

 

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 <= 109
  • 0 <= blacklist.length <- min(105, n - 1)
  • 0 <= blacklist[i] < n
  • All the values of blacklist are unique.
  • At most 2 * 104 calls will be made to pick.

Companies:
Two Sigma, Google

Related Topics:
Hash Table, Math, Binary Search, Sorting, Randomized

Similar Questions:

Solution 1.

Create a mapping between blacked numbers to valid numbers.

Example: n = 7, blacklist=[2,3,5]:

In range: ....
Numbers:  0123456
Blocked:    xx x
Mapped to:  46

In this case, we map 2->4, 3->6.

// OJ: https://leetcode.com/problems/random-pick-with-blacklist/
// Author: github.com/lzl124631x
// Time:
//      Solution: O(BlogB)
//      pick: O(1)
// Space: O(B)
class Solution {
    unordered_map<int, int> m;
    int len;
public:
    Solution(int n, vector<int>& B) {
        len = n - B.size();
        sort(begin(B), end(B));
        int j = lower_bound(begin(B), end(B), len) - begin(B), N = B.size(), next = len;
        for (int i = 0; i < N && B[i] < len; ++i) {
            while (j < N && B[j] == next) ++j, ++next;
            m[B[i]] = next++;
        }
    }
    int pick() {
        int r = rand() % len;
        return m.count(r) ? m[r] : r;
    }
};