Count K-th Roots in a Range Problem
#3932
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3932.
You are given three integers l, r, and k.
An integer y is said to be a perfect k^th power if there exists an integer x such that y = x^k.
Return the number of integers y in the range [l, r] (inclusive) that are perfect k^th powers.
Example 1:
Input: l = 1, r = 9, k = 3
Output: 2
Explanation:
The perfect cubes in the range [1, 9] are:
- 1 = 1^3
- 8 = 2^3
Hence, the answer is 2.
Example 2:
Input: l = 8, r = 30, k = 2
Output: 3
Explanation:
The perfect squares in the range [8, 30] are:
- 9 = 3^2
- 16 = 4^2
- 25 = 5^2
Hence, the answer is 3.
Constraints:
0 <= l <= r <= 10^91 <= k <= 30
Solution
Approach: Enumeration
For k = 1 every integer is a perfect first power, so the answer is r - l + 1.
For larger k, try x = 0, 1, 2, ... and compute y = x^k, stopping as soon as y > r. Each y that lies in [l, r] is counted once (different x give different y). When computing the power, stop multiplying once the value exceeds r, so it never overflows.
Complexity: O(k r1/k) time (about 31 623 values of x for k = 2, and very few for larger k) and O(1) extra space.
class Solution:
def countKthRoots(self, l: int, r: int, k: int) -> int:
if k == 1:
return r - l + 1
ans = 0
x = 0
while x ** k <= r:
if x ** k >= l:
ans += 1
x += 1
return ans