Taro Logo

Pow(x, n)

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+17
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1K views
Topics:
RecursionBit Manipulation

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -104 <= xn <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the valid range of values for $x$ and $n$, and how should we handle potential integer overflow for $n$ (such as when $n = -2^{31}$)?
  2. Should we account for floating-point precision issues or standard IEEE 754 double-precision limitations for the return value?
  3. How should we handle extreme edge cases like $x = 0$ with a negative exponent $n$, which would result in division by zero?
  4. Are there any specific constraints on the time and space complexity, or is the optimal $O(og n)$ approach expected?
  5. Can $x$ be negative, zero, or fractional, and are there any limitations on the magnitude of the result?

Brute Force Solution

Approach

Imagine you need to multiply a number by itself a certain number of times to find the final result. The brute force approach simply starts with the base number and repeatedly multiplies it by itself over and over again until you reach the target count.

Here's how the algorithm would work step-by-step:

  1. Take the starting number and set it aside as your current running total.
  2. Multiply your current running total by the starting number one single time.
  3. Repeat this multiplication process, keeping count of how many times you have multiplied.
  4. If the target count is negative, flip the final result into its fraction form.
  5. Continue multiplying step by step until the exact target count is reached.
  6. Once the total count of multiplications matches the target, stop and use the final accumulated value as your answer.

Code Implementation

class Solution:
    def myPow(self, base_number: float, target_count: int) -> float:
        if target_count == 0:
            return 1.0

        # Handle negative exponents by making the count positive and inverting the base later
        is_exponent_negative = target_count < 0
        absolute_target_count = -target_count if is_exponent_negative else target_count

        running_total = base_number
        current_count = 1

        # Repeatedly multiply the base until we reach the exact target count of multiplications
        while current_count < absolute_target_count:
            running_total = running_total * base_number
            current_count += 1

        # If the target was negative, return the reciprocal fraction form of the final accumulated value
        if is_exponent_negative:
            return 1.0 / running_total

        return running_total

Big(O) Analysis

Time Complexity
O(n) – The brute force approach repeatedly multiplies the base number by itself inside a loop until it reaches the target count n. For a positive exponent n, the algorithm executes the multiplication step exactly n times. If the exponent is negative, it still performs a linear number of multiplications before converting the value to its fraction form. Therefore, the total number of operations grows directly in proportion to the input size n, which simplifies to a linear time complexity of O(n).
Space Complexity
O(log n) – The space complexity is driven entirely by the call stack created during the recursive divide-and-conquer exponentiation process. Because each step halves the target count n, the maximum depth of the recursion stack grows logarithmically relative to the magnitude of n. No additional auxiliary data structures, lists, or hash maps are created, meaning memory usage is strictly tied to this logarithmic recursion depth. As n increases, the maximum number of active stack frames scales proportionally to log n. Ultimately, this simplifies to a Big O space complexity of O(log n).

Optimal Solution

Approach

Instead of multiplying a number by itself over and over again one step at a time, the optimal approach uses a shortcut based on symmetry and doubling. By repeatedly squaring the running total and cutting the remaining number of multiplications in half, we can reach the final answer almost instantly.

Here's how the algorithm would work step-by-step:

  1. Look at the target number of times you need to multiply your base number.
  2. Check if your target number is even or odd.
  3. If the target number is even, group the multiplications into pairs, which means you only need to calculate half that amount and then multiply that result by itself.
  4. If the target number is odd, peel off one multiplication to make the remaining target even, and save it for later.
  5. Keep cutting the target number in half and squaring your working value until you have no multiplications left.
  6. If you had any leftover odd steps along the way, multiply your final result by the original base number to account for them.
  7. Handle special situations where the target number is zero, which always results in one, or when the target number is negative, which means you do the exact same process but ultimately flip the final result into a fraction.

Code Implementation

def my_pow(base_number, target_exponent):
    # Zero exponent always results in one according to mathematical rules.

    if target_exponent == 0:
        return 1.0

    # Negative exponents mean we invert the base and work with positive exponent.

    if target_exponent < 0:
        base_number = 1 / base_number
        target_exponent = -target_exponent

    accumulated_result = 1.0
    current_working_base = base_number

    while target_exponent > 0:
        # Odd exponents require peeling off one factor to make the target even.

        if target_exponent % 2 == 1:
            accumulated_result *= current_working_base

        current_working_base *= current_working_base
        target_exponent //= 2

    return accumulated_result

Big(O) Analysis

Time Complexity
O(log n) – The cost of the algorithm is driven by the exponent n, which is repeatedly halved during each recursive step or iteration. Instead of performing n separate multiplications linearly, the binary exponentiation approach cuts the remaining work in half at every step through squaring. This logarithmic reduction means the number of operations scales proportionally to log base 2 of n. Consequently, the total operations approximate log base 2 of n steps, which simplifies to O(log n).
Space Complexity
O(log n) – The space complexity is determined by the maximum depth of the recursive calls as the target number is repeatedly cut in half. Each division of the target exponent n adds a single stack frame to the call stack until it reaches zero. Therefore, the memory consumed by the recursion stack grows logarithmically relative to the magnitude of the exponent n. Simplifying this to Big O notation yields O(log n) auxiliary space.

Edge Cases

Exponent n is zero
How to Handle:
Return 1.0 immediately since any non-zero number raised to the power of zero equals one.
Exponent n is negative
How to Handle:
Convert n to its positive equivalent and invert x, taking care of minimum integer overflow by using a long integer.
Base x is zero
How to Handle:
Return 0.0 when n is positive, though zero to the power of zero is mathematically undefined and usually handled as 1.
Base x is negative with odd or even exponents
How to Handle:
The binary exponentiation approach naturally preserves the correct sign based on whether n is odd or even.
Base x is 1.0 or -1.0 with extremely large exponents
How to Handle:
Iterative or recursive logarithmic scaling prevents Time Limit Exceeded by running in logarithmic O(log n) time.
Integer n equals Integer.MIN_VALUE (-2147483648)
How to Handle:
Casting n to a 64-bit long integer prevents overflow when negating it to compute the positive exponent.
Result exceeds maximum floating-point limits
How to Handle:
Standard double precision types in the language will automatically handle overflow by returning Infinity or 0.0 underflow.
0/75 completed