Binary Search Searching the answer
244. Nth Root of a Number
You are given an integer n and a list of positive integers ms. For each value m in it, find the
whole number x with xn = m. This x is the exact n-th root of m. If no whole number
works, the answer for that m is -1. Return the answers in the same order as ms.
For example, with n = 3 the value 64 gives 4, because 4 · 4 · 4 = 64. The value 30 gives -1:
33 = 27 is too small and 43 = 64 is too big.
Do not use a built-in power or root function, such as pow or cbrt. An interviewer will ask you to
calculate the root yourself.
Example 1
Input: n = 3, ms = [27, 64, 30, 1000]
[3,4,-1,10]Explanation: 3 · 3 · 3 = 27, 4 · 4 · 4 = 64 and 10 · 10 · 10 = 1000. 30 lies between 27 and 64, so no whole number cubes to it.
Example 2
Input: n = 1, ms = [1, 7, 9000000000000000]
[1,7,9000000000000000]Explanation: With n = 1, x1 = x, so every value is its own root.
Example 3
Input: n = 50, ms = [1, 1125899906842624, 1125899906842623]
[1,2,-1]Explanation: 150 = 1 and 250 = 1,125,899,906,842,624. One less than that has no 50th root, because 1 is too small and 2 is already too big.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 601 ≤ ms.length ≤ 3 × 1041 ≤ ms[i] ≤ 9 × 1015
Clarifying questions
What you would ask an interviewer before writing any code.