Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 <= 1090 <= blacklist.length <= min(105, n - 1)0 <= blacklist[i] < nblacklist are unique.2 * 104 calls will be made to pick.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math · Binary Search
["Solution","pick","pick","pick","pick","pick","pick","pick"] [[7,[2,3,5]],[],[],[],[],[],[],[]]
random-pick-index)random-pick-with-weight)find-unique-binary-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #710: Random Pick with Blacklist
class Solution {
private Map<Integer, Integer> d = new HashMap<>();
private Random rand = new Random();
private int k;
public Solution(int n, int[] blacklist) {
k = n - blacklist.length;
int i = k;
Set<Integer> black = new HashSet<>();
for (int b : blacklist) {
black.add(b);
}
for (int b : blacklist) {
if (b < k) {
while (black.contains(i)) {
++i;
}
d.put(b, i++);
}
}
}
public int pick() {
int x = rand.nextInt(k);
return d.getOrDefault(x, x);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n, blacklist);
* int param_1 = obj.pick();
*/
// Accepted solution for LeetCode #710: Random Pick with Blacklist
type Solution struct {
d map[int]int
k int
}
func Constructor(n int, blacklist []int) Solution {
k := n - len(blacklist)
i := k
black := map[int]bool{}
for _, b := range blacklist {
black[b] = true
}
d := map[int]int{}
for _, b := range blacklist {
if b < k {
for black[i] {
i++
}
d[b] = i
i++
}
}
return Solution{d, k}
}
func (this *Solution) Pick() int {
x := rand.Intn(this.k)
if v, ok := this.d[x]; ok {
return v
}
return x
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(n, blacklist);
* param_1 := obj.Pick();
*/
# Accepted solution for LeetCode #710: Random Pick with Blacklist
class Solution:
def __init__(self, n: int, blacklist: List[int]):
self.k = n - len(blacklist)
self.d = {}
i = self.k
black = set(blacklist)
for b in blacklist:
if b < self.k:
while i in black:
i += 1
self.d[b] = i
i += 1
def pick(self) -> int:
x = randrange(self.k)
return self.d.get(x, x)
# Your Solution object will be instantiated and called as such:
# obj = Solution(n, blacklist)
# param_1 = obj.pick()
// Accepted solution for LeetCode #710: Random Pick with Blacklist
use rand::prelude::*;
use std::collections::HashMap;
use std::collections::HashSet;
struct Solution {
rng: ThreadRng,
map: HashMap<usize, usize>,
m: usize,
n: usize,
}
impl Solution {
fn new(n: i32, mut blacklist: Vec<i32>) -> Self {
let n = n as usize;
let rng = thread_rng();
blacklist.sort_unstable();
let m = blacklist.len();
let set: HashSet<i32> = blacklist.iter().copied().collect();
let mut map: HashMap<usize, usize> = HashMap::new();
let mut j = 0;
for i in n - m..n {
if !set.contains(&(i as i32)) {
map.insert(blacklist[j] as usize, i);
j += 1;
}
}
Solution { rng, map, m, n }
}
fn pick(&mut self) -> i32 {
let x = self.rng.gen_range(0, self.n - self.m);
if let Some(&v) = self.map.get(&x) {
v as i32
} else {
x as i32
}
}
}
// Accepted solution for LeetCode #710: Random Pick with Blacklist
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #710: Random Pick with Blacklist
// class Solution {
// private Map<Integer, Integer> d = new HashMap<>();
// private Random rand = new Random();
// private int k;
//
// public Solution(int n, int[] blacklist) {
// k = n - blacklist.length;
// int i = k;
// Set<Integer> black = new HashSet<>();
// for (int b : blacklist) {
// black.add(b);
// }
// for (int b : blacklist) {
// if (b < k) {
// while (black.contains(i)) {
// ++i;
// }
// d.put(b, i++);
// }
// }
// }
//
// public int pick() {
// int x = rand.nextInt(k);
// return d.getOrDefault(x, x);
// }
// }
//
// /**
// * Your Solution object will be instantiated and called as such:
// * Solution obj = new Solution(n, blacklist);
// * int param_1 = obj.pick();
// */
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.