# Pow(x, n) — Day 68(Python) Photo by Amritanshu Sikdar on Unsplash

Today’s question is a favorite question among Facebook interviewers. Let us look into the question.

50. Pow(x, n)

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

Example 1:

Example 2:

Example 3:

Constraints:

• `-100.0 < x < 100.0`
• `-231 <= n <= 231-1`
• `-104 <= xn <= 104`

We can solve the given problem using recursion.

Since we are using recursion, we need to identify the base condition. What is the minimum valid input? It is when n is equal to 0. When n = 0, the power of that number is 1.

We can notice that “n” can be negative too. What do we do in such a case? We will find the power of the reciprocal of that number.

The recursive call will be as follows.

Let us look into the complete code snippet.

Complexity analysis.

Time Complexity

We are calling the recursive function for “n” times. Hence the time complexity is O(n).

Space Complexity.

We are calling the recursive function for “n” times. Internally recursive calls are stored in a stack. Hence the space complexity is O(n).

If we try to run this program, we will either get maximum recursion reached or the time limit exceeded. How can we try to improve?

We will try solving it in a step by step approach.

We can use two myPow functions and multiply both of them together. Does it sound confusing? Let us look at how it would look like in code.

But we need to keep in mind that the above code can run only when n is even. What about cases when n is odd? Then we need to make it even. How do we do that?

Let us look at the complete code snippet.

If we run this code, we might still get maximum recursion reached or the time limit exceeded. How can we try to improve? Memoization is the answer.

In this case, “n” keeps changing each time. Hence we will have to memoization this value. We can use a dictionary to store the results. Let us look at how we can use memoization and solve this problem.

Complexity analysis.

Time Complexity

We are calling the recursive function for “n/2” times. Hence the time complexity is O(logn).

Space Complexity.

We are calling the recursive function for “n/2” times. Internally recursive calls are stored in a stack. Hence the space complexity is O(logn).

## More from Annamariya Tharayil

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt