Pow(x, n)

MediumDivide & Conquer · Binary Exponentiation🧩 Recursion & Divide and ConquerLeetCode #50 ↗Updated

Problem

Write your own myPow(x, n) that returns the double x raised to the integer power n. The exponent can be negative (meaning 1 / x|n|) and can be as extreme as Integer.MIN_VALUE, so a loop of n multiplications is not an option.
Inputx = 2.0, n = 10Output1024.0
Inputx = 1.5, n = 3Output3.375
Inputx = 4.0, n = -2Output0.0625

-100.0 < x < 100.0  ·  -231 ≤ n ≤ 231-1  ·  x ≠ 0 or n > 0  ·  -104 ≤ xn ≤ 104

Try it yourself

Java
class Solution {
    public double myPow(double x, int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
xn = (xn/2)2 (times one extra x when n is odd). Halving the exponent every step means only about 31 squarings are ever needed, even for n = 231-1.
PatternRecursion & Divide and Conquer

Instinct If the answer for n items can be built from the same problem on halves (or smaller pieces) plus a cheap combine step - split, recurse, merge.

Memory hack Split it, trust it, stitch it - nail the base case, take the leap of faith on smaller calls, then glue their answers together.

Open the Recursion & Divide and Conquer guide →

Approaches

Brute ForceRepeated Multiplication

Time O(|n|)Space O(1)

Multiply an accumulator by x exactly |n| times, then take the reciprocal if n was negative. Widening n to long first makes |Integer.MIN_VALUE| representable.

Java
public double myPow(double x, int n) {
    long e = Math.abs((long) n); // long: |MIN_VALUE| overflows int
    double result = 1.0;
    for (long i = 0; i < e; i++) {
        result *= x;
    }
    return n < 0 ? 1.0 / result : result;
}

Correct, but ~2·109 multiplications for extreme n — times out.

At a glance

LevelApproachTimeSpace
Brute ForceRepeated MultiplicationO(|n|)O(1)
BetterRecursive Fast Power (Halve the Exponent)O(log |n|)O(log |n|)
OptimalIterative Binary ExponentiationO(log |n|)O(1)
Common pitfalls
  • Negating n as an int — -Integer.MIN_VALUE is still negative.
  • Calling power(x, e/2) twice per level — that silently becomes O(n).
  • Forgetting the reciprocal for negative exponents, or taking it after overflow to infinity.
Interview tips
  • Start from the O(n) loop, then ask: “can I reuse xn/2?”
  • Mention the Integer.MIN_VALUE edge case before the interviewer does.
  • Note the same trick powers modular exponentiation and matrix power (Fibonacci in O(log n)).
Pattern
Binary exponentiation (halve the problem) → repeated application of an associative operation a huge number of times.
My notes saved in this browser