Pow(x, n) (LeetCode 50): Solution and Explanation

Medium
Math
Recursion

Compute x raised to the integer power n, where x is a floating point number and n can be negative, zero or positive, without calling a built-in power function.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The direct approach multiplies x by itself n times. That is O(n), and since n can be over two billion in magnitude, it is far too slow. The goal is to reuse work instead of redoing it.

The key fact is that powers can be squared. Once you know x to the 4th, squaring it gives x to the 8th in one multiplication instead of four. In general x to the 2m is the square of x to the m, and x to the 2m + 1 is that square times one more x. Halving the exponent at every step means only about log₂(n) steps are needed.

The iterative version reads this off the binary digits of n. Write n in binary, for example 10 is 1010, which means x to the 10th equals x to the 8th times x to the 2nd. Keep a variable that holds x, then x squared, then x to the 4th, and so on, by squaring it each round. Look at the lowest bit of n each round: if it is 1, multiply that current power into the result. Then shift n right by halving it. When n reaches 0, every set bit has contributed its power.

Negative exponents reduce to positive ones: x to the -n is 1 / x to the n. So the code flips x to its reciprocal and makes n positive before the loop. Zero is handled up front, since anything to the 0th power is 1.

Approach: Iterative exponentiation by squaring

  1. If n == 0, return 1.
  2. If n is negative, replace x with 1 / x and n with -n.
  3. Start with result = 1.
  4. While n > 0, if n is odd, multiply result by the current x, since this bit of n is set.
  5. Square x so it represents the power for the next bit, and halve n with integer division.
  6. When n reaches 0, return result.

Step-by-step example

x = 2.0, n = 10
  1. n is 10, which is 1010 in binary. Start with result = 1.
  2. n = 10 is even, so result stays 1. Square x to 4 and halve n to 5.
  3. n = 5 is odd, so result = 1 × 4 = 4. Square x to 16 and halve n to 2.
  4. n = 2 is even, so result stays 4. Square x to 256 and halve n to 1.
  5. n = 1 is odd, so result = 4 × 256 = 1024. Square x and halve n to 0.
  6. The loop ends and the answer is 1024.0, which is 2 to the 10th.

Code: Python, Java, C++

1class Solution:
2    def myPow(self, x: float, n: int) -> float:
3        if n == 0:
4            return 1
5        if n < 0:
6            x = 1 / x
7            n = -n
8
9        result = 1
10        while n > 0:
11            if n % 2 == 1:  # n is odd
12                result *= x
13            x *= x          # Square x
14            n //= 2         # Halve n
15        return result

Time and space complexity

Time

O(log n)

Each iteration halves n, so the loop runs once per binary digit of n, which is about log₂(n) times, with constant work per iteration.

Space

O(1)

Only x, n and result are updated in place. There is no recursion.

Other approaches

Recursive fast power (time O(log n), space O(log n))

Compute half = myPow(x, n // 2) and return half × half, multiplied by x once more if n is odd. It is the same idea top down and easy to derive, but it uses a call stack of depth log n.

Repeated multiplication (time O(n), space O(1))

Multiply the result by x exactly |n| times. It is correct and trivial but runs out of time for large exponents.

Common mistakes

  • Negating n in a fixed-width integer language. In Java or C++, -n overflows when n is the minimum 32-bit integer, so convert n to a 64-bit long first.
  • Computing myPow(x, n // 2) × myPow(x, n // 2) in a recursive version. Making two calls instead of reusing one result brings the time back to O(n).
  • Forgetting to invert x for negative exponents, which returns a huge number instead of a small fraction.
  • Relying on Python's n // 2 for negative n. It rounds toward negative infinity, which is why the code makes n positive before the loop.

Frequently asked questions

Why is fast power O(log n)?

Each step halves the exponent and does at most two multiplications. An exponent of n can only be halved about log₂(n) times before it reaches 0.

How do you handle a negative exponent in Pow(x, n)?

Use the identity that x to the -n equals 1 / x to the n. Replace x with its reciprocal, make n positive, and run the normal algorithm.

Why does the Java solution cast n to long?

The smallest 32-bit integer has no positive counterpart, so negating it overflows back to itself. Storing n in a 64-bit variable before negating avoids that.

What should Pow(x, n) return when x is 0 and n is negative?

Mathematically that is a division by zero, so the result is undefined. The problem's constraints rule this case out, which is why the reference code does not guard against it. In production code you would raise an error or return infinity explicitly.