Pow(x, n) - Problem
Power Function Implementation

You need to implement your own version of the mathematical power function that calculates xn (x raised to the power of n).

Goal: Given a base number x and an exponent n, return the result of xn.

Key Challenges:
• Handle negative exponents (fractional results)
• Handle large exponents efficiently
• Deal with edge cases like x=0, n=0
• Avoid timeout for large values of n

Example: pow(2, 10) should return 1024, and pow(2, -2) should return 0.25.

Input & Output

example_1.py — Basic Power
$ Input: x = 2.0, n = 10
Output: 1024.0
💡 Note: 2^10 = 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 1024
example_2.py — Negative Exponent
$ Input: x = 2.1, n = 3
Output: 9.261
💡 Note: 2.1^3 = 2.1 × 2.1 × 2.1 = 9.261
example_3.py — Negative Exponent
$ Input: x = 2.0, n = -2
Output: 0.25
💡 Note: 2^(-2) = 1/(2^2) = 1/4 = 0.25

Visualization

Tap to expand
Fast Exponentiation: Computing x^8x^8x^4x^4x^2x^2x^2x^2x^1x^1×square×square×squareTime: O(log n) vs O(n) - Exponentially faster!
Understanding the Visualization
1
Base Case
If n = 0, return 1 (any number^0 = 1)
2
Divide
Compute half_power = x^(n/2) recursively
3
Square
Square the half_power to get x^n
4
Handle Odd
If n is odd, multiply by one extra x
Key Takeaway
🎯 Key Insight: By using the mathematical property x^n = (x^(n/2))^2, we can reduce the problem size by half at each step, achieving logarithmic time complexity instead of linear!

Time & Space Complexity

Time Complexity
⏱️
O(log n)

We divide n by 2 at each recursive step, so we make log n recursive calls

n
2n
Linearithmic
Space Complexity
O(log n)

Recursion depth is log n due to the call stack

n
2n
Linearithmic Space

Constraints

  • -100.0 < x < 100.0
  • -231 ≤ n ≤ 231-1
  • -104 ≤ xn ≤ 104
  • Important: Your solution must handle negative exponents correctly
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28 Apple 22
89.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen