#50

Pow(x, n)

Medium
MathRecursionRecursionExponentiation by Squaring
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log n)
Space
O(1)
O(log n)
💡

Intuition

Time O(log n)Space O(log n)

The optimal approach uses the method of exponentiation by squaring, which reduces the number of multiplications needed. This is efficient for large 'n' and works by breaking down the problem recursively.

⚙️

Algorithm

4 steps
  1. 1Step 1: If n is 0, return 1 (base case).
  2. 2Step 2: If n is negative, convert x to 1/x and n to -n.
  3. 3Step 3: If n is even, recursively calculate myPow(x * x, n / 2).
  4. 4Step 4: If n is odd, return x * myPow(x, n - 1).
solution.py10 lines
1def myPow(x, n):
2    if n == 0:
3        return 1
4    if n < 0:
5        x = 1 / x
6        n = -n
7    if n % 2 == 0:
8        return myPow(x * x, n // 2)
9    else:
10        return x * myPow(x, n - 1)

Complexity note: The time complexity is O(log n) due to the halving of 'n' in each recursive call. The space complexity is O(log n) due to the call stack in recursion.

  • 1Exponentiation by squaring is a powerful technique for reducing the number of multiplications.
  • 2Handling negative exponents by inverting the base is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.