Here, we define a few base-cases that pertain to the rule of math. But the brute force approach to reduce n by 1 every function call and calculate the power gives a TLE.
In this case, the optimization is to use math where ever we can. So, once we reach an even power, instead of decrementing n by 1, we half the value of n, and multiply x by itself. This way, by halving n at every function call, this linear input set is reduced to logarithmic input space.
Fun fact: just returning
x**n
works, lol
Code:
Python3 (brute force)
Python3 (optimized)
Big O Analysis
-
Runtime
The runtime complexity here is . This is because once we reach even power (), we decrement by half and multiply x by itself in that particular function call. Since, we half the input n every call, it’s logarithmic optimization.
-
Memory
The memory usage is , constant space.
— A