Pow(x, n) solution explained
To compute x to the power n quickly, use binary exponentiation: square the base and halve the exponent at each step, multiplying the result by the current base whenever the exponent is odd. Handle a negative n by working with 1/x and the absolute value of n. The Pow(x, n) solution takes O(log n) multiplications instead of n, and O(1) extra space in its loop form.
By Evin JohnPublished 6 min read
The task, restated
Write your own power function. The base x is a floating-point number, and the exponent n is an integer that can be positive, zero or negative, possibly as large in size as a 32-bit integer allows. Return x to the n. The result is compared with a small tolerance, since floating-point arithmetic is involved.
| x | n | Result |
|---|---|---|
| 3 | 5 | 243 |
| 1.5 | -2 | 0.444... (that is 1 / 2.25) |
| -2 | 7 | -128 |
| 7 | 0 | 1 |
| 1.0000001 | 2,147,483,647 | about 1.84 × 10^93 |
Clarify: what should happen for x = 0 with a negative n (division by zero), and what about 0 to the power 0? Many versions promise that case will not appear, or accept 1 for 0^0. Also ask about the range of n, because it decides how you negate it safely.
How interviewers use it
Pow(x, n) is a compact test of divide-and-conquer thinking. The interviewer wants to hear you notice that the work can be halved, then watch how you handle negative exponents and the most negative 32-bit integer. In languages with fixed-size integers, negating -2,147,483,648 overflows, which is a classic trap. It also opens naturally into number theory follow-ups.
- Compute (a^b) mod m for huge b. Same loop, reduce modulo m after each multiplication; this is the core of many cryptography and hashing tasks.
- Fast Fibonacci. Raise a 2 by 2 matrix to the n-th power with the same squaring loop, O(log n) matrix multiplications.
- The exponent is a huge number given as a digit list. Process it digit by digit: result = result^10 · x^digit.
- Integer results only. Discuss overflow and whether to return a big integer.
Brute force: multiply n times
Start from 1 and multiply by x, |n| times. Take the reciprocal at the end if n was negative. That is O(|n|) multiplications, about two billion for the largest inputs, which is too slow for an interview time limit. It is still the right reference to test against for small n.
def power_loop(x, n):
result = 1.0
for _ in range(abs(n)):
result *= x
return 1 / result if n < 0 else resultThe efficient approach: exponentiation by squaring
Write n in binary. x^13 is x^8 · x^4 · x^1, because 13 is 1101 in binary. As you scan the bits from the lowest, keep a base that is x, then x², then x^4, then x^8, squaring each time. Whenever the current bit is 1, multiply that base into the result. There are about log₂ n bits, so about 2 log₂ n multiplications in total.
For a negative exponent, x^-n equals (1/x)^n. Swap x for its reciprocal and make n positive before the loop. In Python, integers do not overflow, so -n is safe. In fixed-width languages, store n in a 64-bit variable first.
def power(x, n):
if n < 0:
x, n = 1 / x, -n
result = 1.0
while n:
if n & 1:
result *= x
x *= x
n >>= 1
return resultfunction power(x, n) {
let base = n < 0 ? 1 / x : x;
let exp = Math.abs(n);
let result = 1;
while (exp > 0) {
if (exp % 2 === 1) result *= base;
base *= base;
exp = Math.floor(exp / 2);
}
return result;
}Why not exp >>= 1 in JavaScript? Bitwise operators convert their operands to 32-bit signed integers, so for an exponent of 2,147,483,648 (the absolute value of the smallest 32-bit integer), 2147483648 >> 1 gives -1,073,741,824 and the loop goes wrong. Division and Math.floor avoid it.
The recursive version
def power_rec(x, n):
if n == 0:
return 1.0
if n < 0:
return 1 / power_rec(x, -n)
half = power_rec(x, n // 2)
return half * half * (x if n % 2 else 1)Compute the half once and square it. Calling the function twice for the two halves brings the cost straight back to O(n).
Time and space
| Version | Time | Extra space |
|---|---|---|
| Repeated multiplication | O(|n|) | O(1) |
| Recursive halving | O(log |n|) | O(log |n|) call stack |
| Iterative squaring | O(log |n|) | O(1) |
Edge cases
- n = 0 returns 1 for any x (agree on 0^0).
- x = 0 with negative n: Python raises a division error, JavaScript returns Infinity. Decide what you want.
- x = 1 or x = -1 with a huge n: the answer is 1 or ±1 depending on parity, and the loop is still fast.
- The most negative 32-bit n, whose absolute value does not fit in 32 bits.
- Results that overflow to infinity or underflow to 0, which floating point handles without an error.
- Small rounding differences: 10 to the -3 computed as (1/10)^3 may print as 0.0010000000000000002. Taking the reciprocal at the end instead often rounds better.
Mistakes to avoid
- Negating n in a 32-bit type when n is the smallest value, which overflows.
- Using bit shifts on large JavaScript numbers.
- Recursing on both halves separately, which is still O(n).
- Forgetting the odd-exponent multiply, so x^5 comes out as x^4.
- Comparing floating results with exact equality in tests.
How to explain it out loud
Fictional example
- Candidate
- Multiplying n times is linear, and n can be two billion. But x to the n is x to the n over 2, squared, so I can halve the exponent each time.
- Candidate
- Iteratively, I look at n's bits from the bottom, square the base each round, and multiply it into the result when the bit is 1. For negative n I flip x to 1 over x first.
- Candidate
- That is log n multiplications and constant space. The one trap is negating the smallest 32-bit integer, so I would widen n first in Java or C++.
Related walkthroughs
Single Number is another problem where a bitwise view of the numbers gives the clean answer. Happy Number also turns a possibly long process into a short, bounded one. Plus One is the arithmetic warm-up that pairs well with this one.
Where Natively fits
When you rehearse on a Mac or Windows PC, Natively can read a math-style coding problem from a screenshot, suggest the squaring approach and remind you to ask about negative exponents and overflow. The transcript of the practice round shows whether you explained the halving before writing code. Read more on the AI interview assistant page.
Questions people ask
How do you implement pow(x, n) efficiently?
Use binary exponentiation: while n is above zero, multiply the result by x when n is odd, square x, and halve n. Use 1/x and the absolute value of n when n is negative.
What is the time complexity of Pow(x, n)?
O(log n) multiplications. The iterative version uses O(1) extra space; the recursive one uses O(log n) stack.
How do you handle negative exponents in pow?
Compute the power of 1/x with the positive exponent. In fixed-width languages, widen n first, because negating the smallest 32-bit integer overflows.
Why not use bit shifts in JavaScript for pow?
Bitwise operators convert to 32-bit integers, so shifting an exponent of 2,147,483,648 gives a negative number. Use division and Math.floor.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
