PPractick

DSA interview question

Pow(x, n) Using Recursion

Easy · Algorithms · Topics: recursion, math, divide and conquer

The problem

A finance calculator needs x^n for compound growth, where x is a double and n can be any 32-bit integer, including negatives (discounting) and huge values. Multiplying x by itself n times takes O(n), which is far too slow for n = 2 billion. The recursive divide-and-conquer idea: compute x^(n/2) once, square it, and multiply by one more x if n is odd. That halves n on every call, so the depth is only about 31.

Example: x = 2.0, n = 10 → 1024.0; x = 2.0, n = -2 → 0.25.

Function signature

double myPow(double x, int n);

Test cases

Input (x, n)OutputExplanation
(2.00000, 10)1024.00000
(2.10000, 3)9.26100
(2.00000, -2)0.250001 / 2²
(1.00000, -2147483648)1.00000n = INT_MIN, whose negation overflows int
(-2.00000, 3)-8.00000An odd power keeps the sign

(Confirm: x is not 0 when n is negative; the result fits in a double; answers within 10⁻⁵ are accepted.)

How interviewers phrase it

Clarifying questions to ask

  1. Can n be negative? Can it be INT_MIN?
  2. Can x be 0 with a negative n? (Assume not.)
  3. What precision is expected?

Follow-ups to expect

  1. "Why not recurse twice on n/2?"
  2. "How do you handle negative n?"
  3. "What's the recursion depth?"
  4. "Iterative version?"
  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