Problem
Implement the function that raises a floating-point number x to an integer power n, including negative exponents. A negative exponent means you compute the positive power and then take the reciprocal.
- Input:
x = 2.00000,n = 10 - Output:
1024.00000 - Explanation: 2 multiplied by itself 10 times equals 1024.
Counter-example to show negative exponents:
- Input:
x = 2.00000,n = -2 - Output:
0.25000 - Explanation: 2^(โ2) = 1 / 2^2 = 1 / 4 = 0.25.
Intuition
The naive approach multiplies x by itself n times, but n can be as large as 2^31 โ 1 โ about 2 billion operations, which will always time out. The key insight is that x^n = (x^(n/2))^2: you can square a half-power instead of doing twice the work. Each recursive call halves the exponent, so the total number of multiplications drops from O(n) to O(log n).
Approach 1 โ Brute Force (Linear)
Convert a negative exponent to its positive form and multiply x by itself that many times. Simple and correct, but infeasible for the given constraints since n can reach 2 billion.
- If
nis negative, replacexwith1/xandnwith-n. - Initialize
result = 1.0. - Multiply
resultbyxexactlyntimes. - Return
result.
1def myPow(x: float, n: int) -> float:
2 if n < 0:
3 x = 1.0 / x
4 n = -n
5 result = 1.0
6 for _ in range(n):
7 result *= x
8 return resultTime: O(n) โ one multiplication per unit of exponent.
Space: O(1) โ a single accumulator variable.
Approach 2 โ Fast Power (Exponentiation by Squaring)
Recurse on half the exponent and square the result. If the exponent is odd, multiply in one extra factor of the base. This gives the same answer with O(log n) multiplications.
- Handle the negative case: convert
nto its absolute value and record the sign. - Base case: any number to the 0th power is 1.0.
- Recurse on
exponent // 2to get the half-result. - If
exponentis even, returnhalfResult * halfResult. - If
exponentis odd, returnhalfResult * halfResult * baseโ the extra factor covers the leftover. - After recursion, if the original
nwas negative return1.0 / result.
1def myPow(x: float, n: int) -> float:
2 def fast_pow(base: float, exponent: int) -> float:
3 if exponent == 0:
4 return 1.0
5 half_result = fast_pow(base, exponent // 2)
6 if exponent % 2 == 0:
7 return half_result * half_result # even: squaring the half covers it
8 return half_result * half_result * base # odd: one extra factor of base remains
9
10 if n < 0:
11 x = 1.0 / x
12 n = -n
13 return fast_pow(x, n)Time: O(log n) โ the exponent halves with every recursive call.
Space: O(log n) โ the call stack depth matches the number of halvings.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Brute Force | O(n) | O(1) | Only for tiny n (n โค ~10^6); fails the given constraints |
| Fast Power | O(log n) | O(log n) | Any time n can be large โ the standard interview solution |
Common Mistakes
- Integer overflow when negating INT_MIN โ in Java and C++,
-Integer.MIN_VALUEwraps back toInteger.MIN_VALUEbecause 2^31 doesn't fit in a 32-bit signed int. Always castntolongbefore negating or callingabs. - Applying the brute-force loop without noticing the constraint โ
ncan be up to 2^31 โ 1 โ 2.1 billion. A loop that runs that many multiplications will time out even in C++. - Floor division with a negative exponent in the recursive helper โ in Python,
-5 // 2 == -3(floors toward negative infinity), not-2. If you forget to convertnto a positive value before recursing, the exponent never reaches 0 and the recursion runs forever. - Using
xfrom the outer scope inside the helper instead ofbaseโ whennwas negative you may have already setx = 1.0 / x. If the recursive helper then refers to the outerxvariable for the odd-case multiply, it uses the inverted base, silently doubling the inversion. - Choosing
exponent == 1as the base case instead ofexponent == 0โ this works for odd exponents but introduces an extra conditional branch and can subtly break the even/odd split logic for edge cases liken = 0.
Related Problems
sqrtxโ uses binary search to find a square root, the same "halve the search space" strategy in a different formvalid-perfect-squareโ binary search over a mathematical function, closely analogous structurepower-of-twoโ checks whether a number is an exact power of two using the same binary properties that make fast exponentiation workmultiply-stringsโ implementing arithmetic operations from scratch, similar theme of building math primitives without using language builtinscount-primesโ another pure-math problem where a naive O(nยฒ) loop is replaced by a smarter O(n log log n) algorithm