470. Implement Rand10() Using Rand7() LeetCode Solution
In this guide, you will get 470. Implement Rand10() Using Rand7() LeetCode Solution with the best time and space complexity. The solution to Implement Rand() Using Rand() problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Implement Rand() Using Rand() solution in C++
- Implement Rand() Using Rand() solution in Java
- Implement Rand() Using Rand() solution in Python
- Additional Resources

Problem Statement of Implement Rand() Using Rand()
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. Please do not use a language’s built-in random API.
Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().
Example 1:
Input: n = 1
Output: [2]
Example 2:
Input: n = 2
Output: [2,8]
Example 3:
Input: n = 3
Output: [3,8,10]
Constraints:
1 <= n <= 105
Follow up:
What is the expected value for the number of calls to rand7() function?
Could you minimize the number of calls to rand7()?
Complexity Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
470. Implement Rand10() Using Rand7() LeetCode Solution in C++
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution {
public:
int rand10() {
int num = 40;
while (num >= 40)
num = (rand7() - 1) * 7 + rand7() - 1;
return num % 10 + 1;
}
};
/* code provided by PROGIEZ */
470. Implement Rand10() Using Rand7() LeetCode Solution in Java
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
class Solution extends SolBase {
public int rand10() {
int num = 40;
while (num >= 40)
num = (rand7() - 1) * 7 + rand7() - 1;
return num % 10 + 1;
}
}
// code provided by PROGIEZ
470. Implement Rand10() Using Rand7() LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.