PPractick

DSA interview question

Find the Nth Root of a Number

Medium · Algorithms · Topics: binary search, math

The problem

A puzzle app asks players whether a given number m is a perfect n-th power, for example whether 4096 is a perfect 6th power (it is: 4⁶), and if so, what the root is. Floating-point pow(m, 1.0/n) gives answers like 3.9999999 that truncate wrongly. The robust method is binary search on the integer root in [1, m], but computing mid^n can overflow even 64 bits for large n, so the power must be computed with an early exit as soon as it passes m.

Example: n = 3, m = 27 → 3; n = 3, m = 9 → -1 (9 isn't a perfect cube).

Function signature

int nthRoot(int n, int m);  // integer r with r^n == m, or -1 if none (1 <= n <= 30, 1 <= m <= 1e9)

Test cases

Input (n, m)OutputExplanation
(2, 9)33² = 9
(3, 9)-12³ = 8 and 3³ = 27 skip over 9
(3, 27)3
(1, 14)14The first root of m is m
(4, 69)-1
(6, 4096)44⁶ = 4096
(30, 1)11^30 = 1
(2, 1000000000)-1√10⁹ ≈ 31622.8

(Confirm: return the exact integer root or -1; no floating-point pow.)

How interviewers phrase it

Clarifying questions to ask

  1. Only integer roots, returning -1 otherwise?
  2. Ranges of n and m? (Decides how to avoid overflow.)
  3. If a decimal answer is needed, what precision?

Follow-ups to expect

  1. "How do you avoid overflow in mid^n?"
  2. "What's the monotonic predicate?"
  3. "What if a decimal root were required?"
  4. "Why not use pow?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in