Link: https://leetcode.com/problems/powx-n
Solution:
Topics: math
Intuition
For this problem, we use a technique called binary exponentiation. This problem also answers the question why exponentiation is logarithmic time complexity.
Basically we use the following 3 mathematical properties:
1.
a = x^n
a = x^2(n/2)
2.
a = x^n
a = x(x^(n-1))
3.
a = x^-n
a = (x^-1)^n
a = (1/x)^n
- The first property is taking a 2 out of the exponent, effectively squaring the base. Note that this only behaves nicely when
n
is even. - The second property is if
n
is odd, we simply decrement the exponent and bring down the multiplication. - The third property is handling the negative
n
case. We simply make it a positive case by extracting a -1 from n, and becausex^-1 = 1/x
, this now becomes a positiven
case.
So by squaring x in the even case, we bring this down to logn
time complexity because n
is exponentially decreasing. Of course the brute force solution is to multiply by x n
times, but if n
is large like in the constraints, then the linear solution will not suffice.
Implementation