LeetCode Problem Workspace
Implement Rand10() Using Rand7()
Generate uniform random numbers from 1 to 10 using only rand7(), applying rejection sampling for consistent probability distribution.
4
Topics
6
Code langs
3
Related
Practice Focus
Medium · Math plus Rejection Sampling
Answer-first summary
Generate uniform random numbers from 1 to 10 using only rand7(), applying rejection sampling for consistent probability distribution.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Math plus Rejection Sampling
This problem tests your ability to map a smaller uniform distribution to a larger one using math and rejection sampling. The key is to generate values from rand7() and combine them to cover a 1-10 range uniformly, rejecting values that would bias the distribution. Efficient handling of retries and minimizing expected calls is critical for optimal performance in interview scenarios.
Problem Statement
You are given an API rand7() that returns a uniform random integer from 1 to 7. Implement a function rand10() that returns a uniform random integer from 1 to 10. You may only call rand7() and cannot use any built-in random number generators. Ensure that each integer from 1 to 10 has equal probability of being returned.
Each test case invokes your implemented rand10() multiple times, represented by an internal argument n indicating the number of calls. For example, if n = 1, your function might return [2]; if n = 2, it could return [2,8]. Your implementation must handle up to 10^5 calls efficiently, while maintaining uniform randomness across all outputs.
Examples
Example 1
Input: n = 1
Output: [2]
Example details omitted.
Example 2
Input: n = 2
Output: [2,8]
Example details omitted.
Example 3
Input: n = 3
Output: [3,8,10]
Example details omitted.
Constraints
- 1 <= n <= 105
Solution Approach
Use Rejection Sampling with Two Calls
Combine two rand7() calls to generate a number between 1 and 49. Accept values 1-40 and map them to 1-10 by modulo 10. Reject numbers above 40 and retry. This ensures uniform probability for each output while minimizing wasted calls.
Optimize Expected Calls
Instead of discarding all out-of-range numbers, reuse the remainder to generate additional values in the next iteration. For example, numbers 41-49 can be transformed into a new 1-9 range and combined with another rand7() call, reducing the expected number of retries.
Ensure Uniform Distribution
Check that every integer from 1 to 10 is equally likely by validating the mapping logic. Any bias in handling rejected numbers or modulo operation can break uniformity. Debug with multiple n values to confirm statistical correctness.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity depends on the expected number of retries caused by rejection sampling, roughly O(1) expected per call. Space complexity is O(1) since no additional structures are needed.
What Interviewers Usually Probe
- Will your solution maintain uniform distribution for all outputs?
- How can you reduce the expected number of rand7() calls in your mapping?
- Explain why simple modulo of a single rand7() call is biased.
Common Pitfalls or Variants
Common pitfalls
- Using rand7() % 10 directly introduces bias.
- Failing to properly reject numbers outside the valid range.
- Not optimizing the reuse of out-of-range values, causing inefficiency.
Follow-up variants
- Implement randN() using randM() for arbitrary N > M with rejection sampling.
- Generate a random number in a non-continuous range using rand7().
- Extend rand10() implementation to return multiple outputs efficiently for large n.
FAQ
Why can't I just use rand7() % 10 to implement rand10()?
Using rand7() % 10 introduces bias because 7 is not divisible by 10, which prevents uniform distribution of outputs.
How does rejection sampling ensure uniform randomness in rand10()?
Rejection sampling discards out-of-range values that would skew probabilities, only accepting values that map evenly to 1-10.
Can the rand10() implementation handle large n efficiently?
Yes, by reusing out-of-range values from previous iterations, the expected number of rand7() calls per rand10() remains low, even for large n.
Is it possible to minimize retries when using rand7() to create rand10()?
Yes, optimizing the transformation of leftover values reduces unnecessary retries, improving efficiency without affecting uniformity.
What pattern does 'Implement Rand10() Using Rand7()' mainly test?
It tests the Math plus Rejection Sampling pattern, requiring careful mapping of a smaller uniform distribution to a larger one without bias.
Solution
Solution 1
#### Python3
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
while 1:
i = rand7() - 1
j = rand7()
x = i * 7 + j
if x <= 40:
return x % 10 + 1Continue Topic
math
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
Math plus Rejection Sampling
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Medium
Stay on this level to stabilize interview delivery.
arrow_forward