Understand
30-second explanation
Build the interview-ready mental model before comparing implementations.
Compute xⁿ in O(log n) using fast (binary) exponentiation: square the base and halve the exponent each step, multiplying the result in only when the current exponent bit is 1. Handle negative n by computing the positive power and returning its reciprocal — but convert n to a long FIRST, because negating INT_MIN (-2³¹) overflows a 32-bit int.
Interview contextWhat is testedWhere candidates slipHow to stand outExplore interview contextHide interview context
What's being tested
Whether you know the O(log n) doubling trick instead of looping n times, can reason about associativity, and — critically — whether you spot the INT_MIN negation overflow when handling negative exponents.
Where candidates slip
Negating n with `n = -n` while n is still a 32-bit int, overflowing on n = -2³¹; or looping n times for an O(n) solution that times out on large exponents.
How to stand out
State the recurrence (x^n = (x^2)^(n/2)), explain why it's O(log n), promote n to long before negating, and mention the same pattern generalizes to modular and matrix exponentiation.
Choose
Compare the available approaches
Use constraints and trade-offs to select the route you can defend in an interview.
Interactive decision treeInteractiveChoose the right approachFirst decision previewCompute xⁿIs n small / bounded?YesNo (n up to 2³¹)Explore the full treeCollapse the tree
Learn & trace
Build each solution step by step
Move from the core idea to a visual trace, implementation, proof, and edge cases.
Approach 1 of 2
Recursive Divide & Conquer
1Hint 1Explore hintHide hint
Naively xⁿ = x · x · … (n times) is O(n). Can you compute xⁿ from a SMALLER power so the work shrinks fast?
2Hint 2Explore hintHide hint
Note xⁿ = (x^(n/2))². If you compute the half-power once and square it, you halve the exponent each call — that's a log-depth recursion.
3Hint 3Explore hintHide hint
Handle odd n by peeling one factor: xⁿ = x · (x^(n/2))² when n is odd. And for negative n, compute x^|n| and return its reciprocal — but convert n to long before negating to dodge INT_MIN overflow.
A · Core idea
The key algebraic identity is xⁿ = (x^(n/2))². Computing the half-power once and squaring it does the work of the full power in a single extra multiply — and since the exponent halves every call, we reach the base case in log₂ n steps instead of n.
Why squaring the half is the whole speedup. Naive exponentiation multiplies x into an accumulator n times — linear work. Divide-and-conquer instead asks: "what if I already knew x^(n/2)?" Then xⁿ is just that value squared. The recursion computes half = pow(x, n/2) once and reuses it twice via half * half, so each level of recursion does constant multiplications and there are only log n levels. That reuse — compute once, square — is the entire reason the exponent collapses logarithmically.
Handling odd exponents. Integer division loses the remainder: for odd n, n/2 rounds down, so (x^(n/2))² gives x^(n-1). We're short exactly one factor of x, so we multiply it back: n odd → x · half · half. For even n no correction is needed. This is the recursive mirror of "multiply in only when the bit is 1".
The negative-exponent trap — and why `long` matters. For n < 0, xⁿ = 1 / x^|n|. The obvious move is n = -n, then compute the positive power and reciprocate. But n can be -2³¹ = -2147483648, and +2147483648 does not fit in a signed 32-bit int — negating it overflows and wraps right back to -2147483648, causing an infinite recursion or wrong sign. The fix is to widen n to a 64-bit long before negating, so 2147483648L is representable. In Python integers are unbounded so this is a non-issue, but you must still call it out for the Java/C++ interviewer.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
x = 2.0, n = 10Interactive diagram
Recursion tree halving the exponent
pow(2,10)Each call halves n; depth is log₂ n. The half-power is computed once and squared.
1024.0C · Code with teaching comments
Reference implementation previewpublic double myPow(double x, int n) { long N = n; if (N < 0) { x = 1 / x; N = -N;Explore the full codeHide the full code
D · Why it works and complexityO(log n) timeO(log n) spaceOpen the invariant and proofExplore the proofHide the proof
xⁿ = (x^(n/2))² is the divide-and-conquer heart: compute the subproblem once, square it, and the exponent halves every level. The odd-n correction (× x) and the negative-n reciprocal are the two bookkeeping details — and the long promotion before negating is the trap that separates a passing solution from a robust one.
ComplexityO(log n) time, O(log n) space — Each recursive call halves n, so the recursion depth is log₂|n|. One multiplication per level → O(log n) time. The call stack is log n deep → O(log n) space.
E · Edge cases and pitfalls5x = 2.0, n = -2147483648 — long N = n makes N = -2147483648; N = -N becomes 2147483648 (fits in long). Without the long, this overflows back to negative.Explore edge casesHide edge cases
Edge cases handled
x = 2.0, n = -2147483648long N = n makes N = -2147483648; N = -N becomes 2147483648 (fits in long). Without the long, this overflows back to negative.x = 1.0, n = 21474836471 to any power is 1; recursion bottoms out quickly with all multiplications equal to 1.
Pitfalls
- Negating n while it's still an int — overflow on n = -2³¹.
- Recomputing pow(x, n/2) twice instead of storing it once — degrades to O(n).
- Forgetting the odd-n extra ×x — gives x^(n-1) for odd exponents.
Approach 2 of 2 · Optimal
Iterative Binary Exponentiation (Optimal)
1Hint 1Explore hintHide hint
Write n in binary. xⁿ is the product of x^(2^k) for every bit k that is set in n. Can you accumulate that product while scanning the bits?
2Hint 2Explore hintHide hint
Keep a running `result = 1` and a `current = x`. Each step: if the lowest bit of n is 1, multiply `result *= current`; then square `current *= current` and shift n right (n /= 2).
3Hint 3Explore hintHide hint
Convert n to long and handle negativity up front (x = 1/x, n = -n). Loop while n > 0. This is the same math as the recursion but with no call stack.
A · Core idea
This is the same doubling math as the recursion, expressed by walking the binary representation of n. Every integer n is a sum of distinct powers of two — its set bits — so xⁿ is the product of x raised to each of those powers: x^(2^0), x^(2^1), x^(2^2), … We generate those squared powers on the fly and multiply in only the ones whose bit is set.
The two state variables. current starts at x and is squared every iteration, so it walks through x¹, x², x⁴, x⁸, … — exactly the x^(2^k) values. result starts at 1 and accumulates the answer. At each step we look at the lowest bit of n: if it's 1, the current squared power belongs in the product, so result *= current. Then we square current and shift n right by one bit (n /= 2) to examine the next bit. When n hits 0, every set bit has contributed and result holds xⁿ.
Why this equals the recursion. The recursive (x^(n/2))² and this square-current-each-step are two views of the same identity. Halving the exponent in the recursion corresponds to shifting n right by a bit here; squaring the half corresponds to squaring current. The iterative form just makes the exponent's binary structure explicit and drops the call stack — turning O(log n) space into O(1) space, which also removes any stack-overflow risk for exponents in the billions.
Negative exponent, same trap. As before, n < 0 means reciprocate: set x = 1/x and make n positive. And again, promote n to a long before negating so -2³¹ doesn't overflow. After that the loop is identical. This iterative skeleton is also the one you extend for modular exponentiation — just take % m after each multiply — and for matrix exponentiation by replacing scalar multiply with matrix multiply.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
x = 2.0, n = 10Interactive diagram
Picking the right approach
n=10 (1010)The decision tree. Pow(x, n) needs the O(log n) doubling branch — looping n times times out.
1024.0C · Code with teaching comments
D · Why it works and complexityO(log n) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
Reading n in binary makes the algorithm obvious: each set bit picks one squared power x^(2^k) to include. result collects the chosen powers, current marches through the powers of two by self-squaring. This O(1)-space loop is the template you reuse verbatim for modular and matrix exponentiation.
ComplexityO(log n) time, O(1) space — n has ~log₂ n bits; we do O(1) work per bit (a compare, maybe a multiply, a square, a shift). So O(log n) time and only a few scalar variables → O(1) space.
E · Edge cases and pitfalls6x = 2.0, n = 0 — Loop body never runs (0 > 0 false); result stays 1.0 — correct for x⁰.Explore edge casesHide edge cases
Edge cases handled
x = 2.0, n = 0Loop body never runs (0 > 0 false); result stays 1.0 — correct for x⁰.x = 0.0, n = 5current = 0, result becomes 0 on the first set bit; returns 0.0.x = 2.0, n = -2147483648long N negates safely to 2147483648; loop runs ~31 times. An int negation here would overflow.
Pitfalls
- Negating n as an int — overflow on -2³¹ before the loop even starts.
- Squaring current AFTER shifting n, or in the wrong order relative to the multiply — keep multiply, then square, then shift.
- Using `result *= x` instead of `result *= current` — loses the doubling and gives wrong powers.
Practice
Try the solution yourself
Edit the optimal implementation, test another input, and observe the result.
Editable code previewpublic double myPow(double x, int n) { long N = n; if (N < 0) { x = 1 / x; N = -N;Explore the playgroundClose the playground
Avoid mistakes
Recognize the interview traps
Understand why common attempts fail before reviewing the corrected implementation.
1INT_MIN negation overflow
n can be -2³¹. Negating it as a 32-bit int wraps back to -2³¹, causing infinite recursion or a wrong result. Promote to long first.
Explore the code comparisonHide the code comparison
INT_MIN negation overflow
n can be -2³¹. Negating it as a 32-bit int wraps back to -2³¹, causing infinite recursion or a wrong result. Promote to long first.
Don't write this
if (n < 0) {
x = 1 / x;
n = -n; // overflow when n == Integer.MIN_VALUE
}Write this instead
long N = n;
if (N < 0) {
x = 1 / x;
N = -N; // safe: 2147483648 fits in a long
}2O(n) loop times out
Multiplying x into an accumulator n times is linear; with n up to ~2.1 billion it TLEs. Use the log-n doubling instead.
Explore the code comparisonHide the code comparison
O(n) loop times out
Multiplying x into an accumulator n times is linear; with n up to ~2.1 billion it TLEs. Use the log-n doubling instead.
Don't write this
result = 1.0
for _ in range(abs(n)):
result *= xWrite this instead
result, current = 1.0, x
while n > 0:
if n & 1:
result *= current
current *= current
n >>= 13Recomputing the half-power
Calling pow(x, n/2) twice (once per occurrence of the square) doubles the recursion at every level, collapsing O(log n) back to O(n).
Explore the code comparisonHide the code comparison
Recomputing the half-power
Calling pow(x, n/2) twice (once per occurrence of the square) doubles the recursion at every level, collapsing O(log n) back to O(n).
Don't write this
return fastPow(x, n / 2) * fastPow(x, n / 2);Write this instead
double half = fastPow(x, n / 2);
return half * half;Revise
Carry the pattern into the interview
Pattern to remember
Fast exponentiation — square the base, halve the exponent
Code pattern to memorize
xⁿ = (x²)^(n/2) if n even
xⁿ = x · (x²)^(n/2) if n odd
x⁻ⁿ = 1 / xⁿ
# in code: long N = n; if N<0: x = 1/x, N = -NRules to remember
- 1Promote n to a `long` before negating —
-INT_MINoverflows a 32-bit int. This is THE bug interviewers wait for. - 2For negative n, take the reciprocal:
x⁻ⁿ = 1 / xⁿ. Either flipx = 1/xonce at the start, or computexⁿand return1 / result. - 3Square the base, halve the exponent every iteration — that's what turns O(n) multiplications into O(log n).
- 4Multiply the running result in only when the exponent is odd (lowest bit set). Even exponents just keep squaring.
- 5n = 0 returns 1 for any x (including x = 0 by convention here). Make sure the loop/recursion bottoms out at 1.
- 6Iterative avoids stack overflow; recursive is cleaner to explain. Both are O(log n) — know both.
Use this pattern when
- Raising to an integer power and naive O(n) multiplication is too slow
- Exponent can be huge (10⁹+) — you need O(log n)
- Modular exponentiation (a^b mod m) — same skeleton, mod each multiply
- Any 'apply an associative operation n times' (matrix power, fast Fibonacci)
Choose another pattern when
- Exponent is tiny / bounded by a small constant → a simple loop is fine and clearer
- Base or exponent is floating/non-integer → use the library `pow` / logarithms
- You only need x² or x³ → just multiply directly, no need for the trick
- Language has a trusted bignum pow and the interview allows it
Interview takeaway
Binary exponentiation is the canonical 'do something n times in log n steps' tool: exploit that the operation is associative and that n's binary representation tells you exactly which squared powers to multiply. The same skeleton powers modular exponentiation, matrix exponentiation, and fast Fibonacci.
Continue
Transfer the pattern to another problem
Use a direct variation or pattern sibling to prove the idea is reusable.
Transferable patternBinary (fast) exponentiation — the canonical divide-and-conquer for repeated associative operations. Recognise it whenever you must apply something n times and n is large: scalar power, modular power (a^b mod m), matrix power (fast Fibonacci). Square the operand, halve the exponent, multiply in on set bits.
Practice queueDirect variations and pattern siblings
Direct follow-ups
- Super PowComing soonExponent is a huge array of digits — modular fast exponentiation, process digits with a^(10b+d) = (a^b)^10 · a^d.
- Sqrt(x)The inverse — find the integer whose square is ≤ x via binary search.
- Count Good NumbersComing soonDirect application of modular fast exponentiation under a prime modulus.
- Fibonacci NumberComing soonMatrix exponentiation gives O(log n) Fibonacci using the same doubling skeleton.