Python 0470.py
class Solution:
def rand10(self):
sum = 0
for i in range(10):
sum += rand7() - 1
return 1 + sum % 10
Difficulty
and has an acceptance rate of about 46% (200k+ submissions).
Typical patterns to solve this problem:
- Math
- Probability And Statistics
- Randomized
- Rejection Sampling
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 method named rand10 that produces a pseudo-random integer uniformly distributed in the range 1 to 10. It leverages an existing helper function rand7, which returns an integer uniformly distributed between 1 and 7. By aggregating multiple calls to rand7 and applying arithmetic transformations, the method maps the broader range of possible sums onto the desired 1-10 interval.
Detailed Walkthrough
The method begins by establishing an accumulator variable that will hold the cumulative result of several rand7 invocations.
sum = 0
A for loop iterates exactly ten times. During each iteration, rand7 is called, its result is shifted down by one to produce a zero-based value, and this value is added to the accumulator.
for i in range(10):
sum += rand7() - 1
After the loop completes, the accumulator contains a value ranging from 0 (up to ten calls each returning 1) to 60 (up to ten calls each returning 7). The final step reduces this range to the target interval by applying the modulo operator with divisor 10, then offsetting the result by 1 to convert the zero-based remainder into the required 1-10 range.
return 1 + sum % 10
The combination of these three code fragments constitutes the core logic of the method.
Edge Cases Handled
Because each rand7 call yields a value in the closed interval [1, 7], subtracting 1 guarantees a non-negative contribution (0 to 6) to the accumulator. Consequently, the sum can never be negative, and the modulo operation always receives a non-negative dividend. The modulo operation inherently wraps any sum, whether it is at the lower bound (0) or the upper bound (60), into a remainder between 0 and 9. Adding 1 then maps this remainder to the full inclusive range 1 to 10, ensuring that even extreme accumulator values are correctly transformed without overflow or underflow concerns.
Performance Optimizations
The implementation fixes the number of rand7 calls to ten, eliminating the need for a conditional loop that repeats until a certain condition is met. This deterministic iteration count simplifies control flow and enables the Python interpreter to optimize loop execution. The use of a single accumulator variable avoids the overhead of creating intermediate data structures. Arithmetic operations-subtraction, addition, and modulo-are executed in constant time and are highly optimized at the interpreter level. By performing the modulo reduction only once after all contributions have been summed, the method minimizes the number of expensive division operations, further enhancing runtime efficiency.
ELI5 - Simplified Explanation
Imagine having a magic box that gives you a number between one and seven every time you press a button. That is what rand7 does. This code wants to make a new game where you get a number between one and ten instead. To do this, it presses the button on the first magic box ten times in a row. It adds all those little numbers together to create a big pile of numbers. Then, it uses a special trick with division to chop that big pile down until it fits perfectly into the size of ten. This makes sure that every number from one to ten has a fair chance of being picked.
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 | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 384: Shuffle an Array
- problem 478: Generate Random Point in a Circle
Solved On The Same Day
- problem 455: Assign Cookies
- problem 500: Keyboard Row
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1071: Greatest Common Divisor of Strings
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1748: Sum of Unique Elements
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 216: Combination Sum III
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 503: Next Greater Element II
- problem 556: Next Greater Element III
- problem 622: Design Circular Queue
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
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