Problem 710

Abstract / Summary

Pick a random number from a list avoiding excluded numbers each time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
18 lines | 570 bytes | submitted September 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 35% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Hash Table
  • Math
  • Randomized
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.limit filters 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 while loop guarantees that the chosen outside value is not itself blacklisted, thereby preserving the invariant that every mapped target is a valid pick.
  • Each increment of outside moves 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 blacklist is empty, self.limit becomes n-1, self.change stays empty, and pick simply returns a uniformly random number from the full range.
  • Blacklist entries larger than the limit - Values greater than self.limit are ignored during mapping because they can never be generated by randint. This avoids unnecessary work and keeps the mapping dictionary minimal.
  • Consecutive blacklisted numbers near the limit - The while loop that advances outside skips 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.limit becomes 0. The random generator will always produce 0, and if 0 is 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 candidate outside value is permissible.
  • Dictionary for redirection - Storing mappings in self.change enables constant-time translation from a blacklisted index to its safe counterpart during each pick call.
  • Single pass over blacklist - The preprocessing loop touches each blacklisted element at most once, and the outside pointer 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 outside values, 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.73 | σ = 1.68

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
26 links | 14 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

5 medium
6 solutions   September 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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