TRT
Sign in
hardExpertLeetCode#remap into a dense range#hash map

Random pick with blacklist

Pick uniformly from 0 to n − 1 excluding a blacklist, with one random call per pick, by remapping blacklisted values through a hash map.

The Runtime Theory Team1 min read
Taught inExpected cost of hashingPro — members onlyHash tables are O(1) only in expectation, and only if the hash function spreads keys well. Choosing the function at random from a universal family makes that expectation hold for every set of keys, which is also the defense against hash-flooding attacks.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inSolution(7, [2, 3, 5]), pick() called many times

outeach of 0, 1, 4 and 6 about a quarter of the time

inSolution(3, [0, 1]), pick()

out2

inSolution(1, []), pick()

out0

Given n and a list of blacklisted integers in [0, n), pick() returns a uniformly random integer in [0, n) that isn't blacklisted. n can be up to a billion, and the blacklist up to 100,000 values. Minimize calls to the random number generator.

Before you code

There are k = n − len(blacklist) allowed values. If you draw uniformly from 0 to k − 1, which draws land on blacklisted values, and where could they be sent instead?

Hints

  1. Draw r uniformly from [0, k).
  2. Some values below k are blacklisted, and exactly as many values at or above k are allowed. Pair them up.
  3. Store the pairing in a hash map from each blacklisted value below k to an allowed value at or above k. pick returns map.get(r, r): one random call and one expected O(1) lookup.

Production & complexity notes

When solving Random pick with blacklist on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Expected cost of hashing to reinforce the underlying pattern.

What it practices

Using expected O(1) hash lookups to make sampling exact, from Expected cost of hashing.

Not started

Sign in to save your learning progress.

Sign in to save