#470
Implement Rand10() Using Rand7()
MediumMathRejection SamplingRandomizedProbability and StatisticsRejection SamplingRandomized Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
To minimize calls to rand7(), we can use a rejection sampling technique that allows us to generate numbers uniformly from 1 to 10 without excessive calls.
⚙️
Algorithm
3 steps- 1Step 1: Call rand7() twice to generate a number in the range [1, 49].
- 2Step 2: Map this number to a number between 1 and 10. If the number is greater than 40, discard it and repeat.
- 3Step 3: Return the mapped number.
solution.py7 lines
1def rand7(): ... # Assume this is provided
2
3def rand10():
4 while True:
5 num = (rand7() - 1) * 7 + rand7() # Generates a number from 1 to 49
6 if num <= 40:
7 return (num - 1) % 10 + 1ℹ
Complexity note: This approach has a time complexity of O(n) on average because we are more likely to get a valid number with fewer calls to rand7(). The rejection sampling reduces the number of calls significantly.
- 1Using multiple calls to rand7() can help expand the range of numbers we can generate.
- 2Rejection sampling is an effective technique to ensure uniform distribution while minimizing unnecessary calls.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.