Math Fundamentals18 sections · 814 units
Open in Course

Problem - Power Function (Entry problem)

LeetCode 50

Compute xnx^n (x raised to the power nn). The naive approach multiplies xx by itself nn times, which takes O(n)O(n) time.

But you can do better using logarithms. The key observation: xn=(xn/2)2x^n = (x^{n/2})^2 when nn is even. This lets you halve the exponent at each step.

Before reading the solution, think about this: how many times can you halve nn before reaching 11? That's your clue to the time complexity.