Random Pick with Blacklist
Problem (restated)
Pick uniformly from [0, n) excluding a blacklist. n can be 10^9, so you cannot allocate [0, n).
Intuition
Let m = n - |blacklist|: the whitelist size. Draw in [0, m). Any blacklisted value that sits inside [0, m) is remapped to a whitelist value in the tail [m, n). White values in [0, m) stay themselves.
Approaches
Map blacklist to white tail
UnverifiedIdea. Put the blacklist in a set. Walk the tail from n-1 downward, skipping black numbers, and assign each black b < m a remaining white tail slot. pick: x = rand(m); return map.get(x) ?? x.
Walkthrough. n=7, blacklist [2,3,5]. m=4. Tail whites 4,6. Map 2→6, 3→4. Draws 0..3 become 0,1,6,4.
Trade-offs. Rejection sampling (retry while black) is simple when the blacklist is tiny versus n, but worst-case retries explode when most of [0, n) is banned. The remap is O(1) worst-case.
export class Solution {
private m: number;
private map: Map<number, number>;
constructor(n: number, blacklist: number[]) {
this.m = n - blacklist.length;
this.map = new Map();
const black = new Set(blacklist);
let w = n - 1;
for (const b of blacklist) {
if (b >= this.m) continue;
while (black.has(w)) w--;
this.map.set(b, w);
w--;
}
}
pick(): number {
const x = Math.floor(Math.random() * this.m);
return this.map.get(x) ?? x;
}
}
export class Solution {
private m: number;
private map: Map<number, number>;
constructor(n: number, blacklist: number[]) {
this.m = n - blacklist.length;
this.map = new Map();
const black = new Set(blacklist);
let w = n - 1;
for (const b of blacklist) {
if (b >= this.m) continue;
while (black.has(w)) w--;
this.map.set(b, w);
w--;
}
}
pick(): number {
const x = Math.floor(Math.random() * this.m);
return this.map.get(x) ?? x;
}
}
Template connection
Rejection / blacklist on the Reservoir Sampling page: a uniform draw into valid index space, same virtual-swap idea as LC 519.
Reflection
- The white count is
nminus the blacklist. Draw in[0, white). A black index inside that range is mapped to a white cell in the tail. - While building the map, walk the tail down from
n - 1and skip black cells.picknever returns a black index. - An empty blacklist is an ordinary draw. One white cell is the only answer. Mapping the same black index twice must not inflate the map.