Heyyooo my lovely,
I see you working hard. Kudos!!! Your being tells me how you will invest time into the important things. Give yourself a pat on the back, and we will get into the solution.
Problem
Implement pow(x, n), which calculates x
raised to the power n
(i.e., x^n
). You can’t use any built-in functions aside from basic mathematical operators.
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/2^2 = 1/4 = 0.25
[FREE SUBS]To buy the solution for this problem, use any of the following links. The price is 3 USD. Once you send the payment, message me on IG, LinkedIn, Twitter, or by Email:
Venmo: https://account.venmo.com/u/FNU-Devansh
Paypal: paypal.me/ISeeThings
Or you can sign up for a Free Trial Below. Only 15 days left in this offer -
Step 1: Simple Solution
Since the problem is so straightforward, we can skip straight to the brute force solution. Both the definitions of positive and negative powers are pretty simple. However, as we always discuss on this newsletter, figuring out a simple brute-force solution is a good step to figuring out the main solution. Often the simple answer is only a few tweaks away from the efficient one.
From a cynical perspective, going from the brute force first also has two other benefits in your interview.
This way you’re always talking, and there is less silence. This can be huge for impressing your interviewer. Especially when you want to buy time to come up with your solution.
By going step by step, you can show a more organized problem-solving approach. This gets those big tech interviewers all hot and bothered and will work in your favor. Going straight to the main solution can make it seem like you have memorized the solution, which is a big turn-off.
The brute force solution here comes straight from the definition of the exponents.
if(n==0): return 1 #x^0 is one
if(x==0): return 0
res=1
for i in (0,abs(n)){
res*=x
}
if(n<0): return 1/res
return res
Nothing too funky going on here. The second if statement is just a small optimization you can make for a base case. If you want to show off your math knowledge, you can always ask the interviewer what 0^0 should return.
This will not come as a shock, but our current solution is linear time. We can speed it up using some math.
Keep reading with a 7-day free trial
Subscribe to Technology Made Simple to keep reading this post and get 7 days of free access to the full post archives.