oneby7

Binary Search Searching the answer

244. Nth Root of a Number

Medium

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]

Output: [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]

Output: [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]

Output: [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.

n = 2, ms = [15, 16, 17]

Constraints

  • 1 ≤ n ≤ 60
  • 1 ≤ ms.length ≤ 3 × 104
  • 1 ≤ ms[i] ≤ 9 × 1015

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.