Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Be sure that you clarify the input and output parameters of the problem:
Run through a set of example cases:
HAPPY CASE
Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
EDGE CASE
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
We can implement fast modulo exponentiation either in a recursive manner or iteratively. In fast modulo exponentiation, we multiply the base in the power of 2. By this, we meant that we keep on multiplying the base by itself. So, in the first step, the base becomes squared of itself.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Convert exponent in binary format and keep on multiplying the bases as per the exponent binary format. If we just use the normal way of calculation, when face 1 to the power of 10000, the computation complexity is too high. Consider this way: if we want to get 2^10.
2^10 = 2^4 * 2^4 *2^2
2^4 = 2^2*2^2
2^2 = 2*2
1. Break into base case where n = 0 or n = 1 or n = -1
2. recurrent relations where n is even or odd numbers.
⚠️ Common Mistakes
When n is odd, pow(x, n) = x * pow(x, n-1)
When n is even, pow(x, n) = pow(x, n/2) * pow(x, n/2).
Note when x is equal with 1.0, we could do a optimization here.
Another corner case is when n is -2^31, -n will trigger a integer overflow.
Implement the code to solve the algorithm.
class Solution:
def myPow(self, x, n):
# Break into base case where n = 0 or n = 1 or n = -1
if n == 0:
return 1
if n == 1:
return x
if n == -1:
return 1 / x
# recurrent relations where n is even or odd numbers.
result = self.myPow(x, n // 2)
return result * result * (x if n % 2 else 1)
class Solution {
public double myPow(double x, int n) {
// Break into base case where n = 0 or x = 0 or or x == 1 or n = 1
if (n == 0) {
return 1;
}
if (x == 0 || x == 1 || n == 1) {
return x;
}
// recurrent relations where n is even or odd numbers.
double num = myPow(x, n / 2);
if (n % 2 == 0) {
return num * num;
} else {
if (n < 0) {
return num * num / x;
} else {
return num * num * x;
}
}
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.