Implement Rand10() Using Rand7() — LeetCode 470 Python Solution

MediumMathRejection SamplingProbability and StatisticsRandomized
Problem
#470
Reading time
3 min

The problem

Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API.

Example

Input
n = 1
Output
[2]

Python solution

Python
# 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 + 1

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 470. Implement Rand10() Using Rand7() is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 470. Implement Rand10() Using Rand7()?
LeetCode 470. Implement Rand10() Using Rand7() is rated Medium on LeetCode.
What topics does LeetCode 470. Implement Rand10() Using Rand7() cover?
LeetCode 470. Implement Rand10() Using Rand7() is tagged Math, Rejection Sampling, Probability and Statistics and Randomized on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview