SDE & MLE Prep

470. Implement Rand10() Using Rand7()

Problem

Using only the given API rand7(), which returns a uniform random integer from 1 to 7, implement rand10(), which returns a uniform random integer from 1 to 10.

Example: many calls to rand10() → each of 1…10 about 10% of the time

Constraints: follow-up: minimise the expected number of rand7() calls.

(rand7() − 1) · 7 + rand7() is uniform on 1..49. Accept values ≤ 40 (a multiple of 10) and return (v − 1) % 10 + 1; otherwise retry. Expected ~2.45 calls to rand7 per rand10.

Complexity: O(1) expected.

class Solution:
    def rand10(self) -> int:
        while True:
            v = (rand7() - 1) * 7 + rand7()     # rand7 provided by LeetCode
            if v <= 40:
                return (v - 1) % 10 + 1