710. Random Pick with Blacklist

1. Description

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.

2. Example

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

3. 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 to pick.

4. Solutions

My Accepted Solution(Follow Up)

n = blacklist.size()

class Solution {
private:
    unordered_map<int, int> valid_number;
    int valid_bound;

public:
    Solution(int n, vector<int> &blacklist) {
        // Time complexity(MyListNode): O(n)
        // Space complexity(get): O(n)

        // the range of n is [1, 10^9]
        // while the range of blacklist length is [0, min(10^5, n)]
        // so if the n is very large, most numbers are not in the blacklist
        valid_bound = n - blacklist.size();
        unordered_map<int, bool> in_list_beyond_bound;
        for (auto number : blacklist) {
            if (number >= valid_bound) {
                in_list_beyond_bound[number] = true;
            }
        }

        int candidate = valid_bound;
        for (auto number : blacklist) {
            if (number < valid_bound) {
                while (in_list_beyond_bound[candidate]) {
                    ++candidate;
                }

                valid_number[number] = candidate;
                ++candidate;
            }
        }
    }

    int pick() {
        // Time complexity(MyListNode): O(1)
        // Space complexity(get): O(1)

        int valid_random = rand() % valid_bound;
        return valid_number[valid_random] == 0 ? valid_random : valid_number[valid_random];
    }
};
comments powered by Disqus