894. Random Pick with Blacklist
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a system that can randomly pick an integer from the range [0, n-1] that is not in a given blacklist. All valid integers (whitelisted numbers) must have an equal probability of being chosen. The key constraints are that n can be very large (up to 10^9), making it impossible to store all whitelisted numbers, and we must minimize calls to the random function.
Solution
Random Pick with Blacklist in Python
class Solution:
def __init__(self, n: int, blacklist: List[int]):
# The number of whitelisted integers.
self.whitelist_len = n - len(blacklist)
self.mapping = {}
# Store blacklisted numbers >= whitelist_len in a set for fast lookup.
# These are the only numbers that can conflict with our "fillers".
later_blacklist = {b for b in blacklist if b >= self.whitelist_len}
# `last` is the pointer for the next available "filler" from the top of the range.
last = n - 1
# Iterate through original blacklist to find "holes" (blacklisted numbers < whitelist_len).
for b in blacklist:
if b < self.whitelist_len:
# Find a non-blacklisted filler for this hole.
# The `while` loop finds the next available whitelisted number from the end.
while last in later_blacklist:
last -= 1
# Map the hole to the filler.
self.mapping[b] = last
# This filler is now used, so move to the next potential one.
last -= 1
def pick(self) -> int:
# Generate a random index in the range of whitelisted numbers [0, W-1].
# random.randint is inclusive, so the range is correct.
k = random.randint(0, self.whitelist_len - 1)
# If k is a blacklisted number (a "hole"), return its mapped value.
# Otherwise, k itself is a valid whitelisted number.
return self.mapping.get(k, k)
# Your Solution object will be instantiated and called as such:
# obj = Solution(n, blacklist)
# param_1 = obj.pick()
Random Pick with Blacklist in Java
class Solution {
private Map<Integer, Integer> mapping;
private int whitelistLen;
private Random rand;
public Solution(int n, int[] blacklist) {
this.whitelistLen = n - blacklist.length;
this.mapping = new HashMap<>();
this.rand = new Random();
// Store blacklisted numbers >= whitelistLen for efficient lookup.
// These are the only numbers that can conflict with our "fillers".
Set<Integer> laterBlacklist = new HashSet<>();
for (int b : blacklist) {
if (b >= this.whitelistLen) {
laterBlacklist.add(b);
}
}
// `last` points to the next potential "filler" from the top of the range.
int last = n - 1;
// Iterate through original blacklist to find "holes" (blacklisted numbers < whitelistLen).
for (int b : blacklist) {
if (b < this.whitelistLen) {
// Find a non-blacklisted filler for this hole.
while (laterBlacklist.contains(last)) {
last--;
}
// Map the hole to the filler.
this.mapping.put(b, last);
// Use this filler, so move to the next one.
last--;
}
}
}
public int pick() {
// Generate a random integer in the range [0, whitelistLen-1].
int k = rand.nextInt(this.whitelistLen);
// If k is a remapped blacklisted number, return its mapping.
// Otherwise, k is a valid whitelisted number.
return this.mapping.getOrDefault(k, k);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n, blacklist);
* int param_1 = obj.pick();
*/
Random Pick with Blacklist in C++
class Solution {
private:
std::unordered_map<int, int> mapping;
int whitelist_len;
// Use a good random number generator
std::mt19937 gen;
std::uniform_int_distribution<> distrib;
public:
Solution(int n, std::vector<int>& blacklist) {
whitelist_len = n - blacklist.size();
// Store blacklisted numbers >= whitelist_len for efficient lookup.
// These are the only numbers that can conflict with our "fillers".
std::unordered_set<int> later_blacklist;
for (int b : blacklist) {
if (b >= whitelist_len) {
later_blacklist.insert(b);
}
}
// `last` points to the next potential "filler" from the top of the range.
int last = n - 1;
// Iterate through original blacklist to find "holes" (blacklisted numbers < whitelist_len).
for (int b : blacklist) {
if (b < whitelist_len) {
// Find a non-blacklisted filler for this hole.
while (later_blacklist.count(last)) {
last--;
}
// Map the hole to the filler.
mapping[b] = last;
// Use this filler, so move to the next one.
last--;
}
}
// Initialize random number generator. Constraint n - blacklist.length >= 1 ensures whitelist_len > 0.
std::random_device rd;
gen = std::mt19937(rd());
distrib = std::uniform_int_distribution<>(0, whitelist_len - 1);
}
int pick() {
// Generate a random index in the range [0, whitelist_len - 1].
int k = distrib(gen);
// If k is a remapped blacklisted number, return its mapping.
// Otherwise, k is a valid whitelisted number.
auto it = mapping.find(k);
if (it != mapping.end()) {
return it->second;
}
return k;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(n, blacklist);
* int param_1 = obj->pick();
*/
Random Pick with Blacklist in TypeScript
class Solution {
private mapping: Map<number, number>;
private whitelistLen: number;
constructor(n: number, blacklist: number[]) {
this.whitelistLen = n - blacklist.length;
this.mapping = new Map<number, number>();
// Store blacklisted numbers >= whitelistLen for efficient lookup.
// These are the only numbers that can conflict with our "fillers".
const laterBlacklist = new Set<number>();
for (const b of blacklist) {
if (b >= this.whitelistLen) {
laterBlacklist.add(b);
}
}
// `last` points to the next potential "filler" from the top of the range.
let last = n - 1;
// Iterate through original blacklist to find "holes" (blacklisted numbers < whitelistLen).
for (const b of blacklist) {
if (b < this.whitelistLen) {
// Find a non-blacklisted filler for this hole.
while (laterBlacklist.has(last)) {
last--;
}
// Map the hole to the filler.
this.mapping.set(b, last);
// Use this filler, so move to the next one.
last--;
}
}
}
pick(): number {
// Generate a random integer in the range [0, whitelistLen-1].
const k = Math.floor(Math.random() * this.whitelistLen);
// If k is a remapped blacklisted number, return its mapping.
// Otherwise, k is a valid whitelisted number. `??` handles cases where get returns undefined.
return this.mapping.get(k) ?? k;
}
}
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(n, blacklist)
* var param_1 = obj.pick()
*/
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.