Python 0710.py
class Solution:
def __init__(self, n: int, blacklist: List[int]):
self.limit = n - 1 - len(blacklist)
self.change = {}
outside = self.limit
avoid = set(blacklist)
shuffle(blacklist)
for b in blacklist:
if b <= self.limit:
outside += 1
while outside in avoid:
outside += 1
self.change[b] = outside
def pick(self) -> int:
r = randint(0, self.limit)
return self.change[r] if r in self.change else r
Difficulty
and has an acceptance rate of about 35% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Hash Table
- Math
- Randomized
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a random number picker that excludes a given blacklist of integers from the range [0, n). The constructor prepares a compact representation that enables each call to pick to return a valid number in constant time. The implementation relies on a mapping (self.change) that redirects any blacklisted value that falls inside the usable range to a safe value located beyond that range. The design carefully handles several edge conditions and incorporates optimizations that keep both preprocessing and selection fast.
Initialization
The constructor receives the total size n and a list blacklist. It first computes the highest index that can be returned directly without any mapping:
self.limit = n - 1 - len(blacklist)
If the blacklist is empty, self.limit equals n-1, meaning the entire original range is available. When the blacklist is non-empty, self.limit shrinks accordingly, reserving space for the blacklisted entries.
A dictionary self.change is created to store the redirection from blacklisted indices to valid alternatives:
self.change = {}
Two auxiliary variables are prepared: outside starts at the current limit and will be moved upward to locate safe numbers, while avoid holds the blacklist as a set for O(1) membership checks:
outside = self.limit
avoid = set(blacklist)
The blacklist list is shuffled before processing:
shuffle(blacklist)
Randomizing the order of iteration helps to avoid pathological patterns where many consecutive blacklisted values would otherwise force a long linear scan for each mapping.
Mapping Blacklist Entries
The core of the preprocessing loop iterates over each blacklisted value b. For values that lie within the usable range (b <= self.limit), a mapping is required because such numbers could be produced by the random generator. The code increments outside until it finds a number not present in the blacklist, then records the redirection:
for b in blacklist:
if b <= self.limit:
outside += 1
while outside in avoid:
outside += 1
self.change[b] = outside
Key aspects of this step:
- The condition
b <= self.limitfilters out blacklist entries that are already beyond the usable range; those entries never need a mapping because the random generator never produces them. - The inner
whileloop guarantees that the chosenoutsidevalue is not itself blacklisted, thereby preserving the invariant that every mapped target is a valid pick. - Each increment of
outsidemoves the pointer forward permanently; no number is examined more than once across all iterations, ensuring linear total work relative to the size of the blacklist.
Random Selection
The pick method draws a random integer r uniformly from the interval [0, self.limit]. Because self.limit already excludes the count of blacklisted numbers, the raw random value is guaranteed to be within the domain that may need redirection:
r = randint(0, self.limit)
If r appears in the mapping dictionary, the method returns the precomputed safe alternative; otherwise it returns r unchanged:
return self.change[r] if r in self.change else r
This conditional lookup is performed in constant time thanks to the dictionary structure.
Edge Cases Handled
The implementation gracefully manages several boundary situations:
- Empty blacklist - When
blacklistis empty,self.limitbecomesn-1,self.changestays empty, andpicksimply returns a uniformly random number from the full range. - Blacklist entries larger than the limit - Values greater than
self.limitare ignored during mapping because they can never be generated byrandint. This avoids unnecessary work and keeps the mapping dictionary minimal. - Consecutive blacklisted numbers near the limit - The
whileloop that advancesoutsideskips over any blacklisted numbers that would otherwise be selected as mapping targets, ensuring that every returned value is truly outside the blacklist. - All but one number blacklisted - In the extreme case where only a single number is allowed,
self.limitbecomes0. The random generator will always produce0, and if0is blacklisted it will be mapped to the sole remaining valid number, guaranteeing a correct result.
Performance Optimizations
Several design choices contribute to the efficiency of the solution:
- Set for blacklist membership - Converting the blacklist to a set (
avoid) provides O(1) checks when determining whether a candidateoutsidevalue is permissible. - Dictionary for redirection - Storing mappings in
self.changeenables constant-time translation from a blacklisted index to its safe counterpart during eachpickcall. - Single pass over blacklist - The preprocessing loop touches each blacklisted element at most once, and the
outsidepointer moves monotonically forward, preventing repeated scans of the same numbers. - Shuffling the blacklist - Randomizing the order of processing spreads out the work of finding valid
outsidevalues, reducing the likelihood of long consecutive scans in worst-case input orders. - Compact limit calculation - By reducing the random range to
self.limit + 1, the algorithm eliminates the need for rejection sampling, which could otherwise cause variable-time behavior.
Overall, the class achieves O(len(blacklist)) preprocessing time and O(1) time per pick operation, while using O(len(blacklist)) additional space for the mapping dictionary. The careful handling of edge conditions and the use of hash-based data structures ensure both correctness and speed across a wide variety of input scenarios.
ELI5 - Simplified Explanation
Imagine a big, magical chest filled with numbered balls. Some of these balls are special and are not allowed to be picked, so they are kept in a separate bag outside the chest. When picking a ball, the goal is to make sure every allowed ball has an equal chance of being pulled out.
The code starts by figuring out how many allowed balls are left after removing the ones from the forbidden list. It sets a limit so that the computer only looked at the fair balls.
Inside the chest, some of the balls in the front might be on the forbidden list. To solve this, the computer keeps a little notebook. When it spots a forbidden ball where a good ball should be, it uses the notebook to remember to swap that bad ball with a good one from the very end of the line.
When it is time to pick, the computer reaches into the chest and grabs a random number. It checks the notebook to see if that specific number is one that needs to be swapped. If it finds a note about that number, it swaps it for the good ball it wrote down earlier. If there is no note, the ball is safe to pick and is given out.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 398: Random Pick Index
- problem 528: Random Pick with Weight
- problem 1980: Find Unique Binary String
Solved On The Same Day
- problem 621: Task Scheduler
- problem 636: Exclusive Time of Functions
- problem 676: Implement Magic Dictionary
- problem 677: Map Sum Pairs
- problem 1658: Minimum Operations to Reduce X to Zero
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality