TRT
Sign in
mediumCoreLeetCode#fast exponentiation#halving

Pow(x, n)

Compute x to the power n with O(log n) multiplications by halving the exponent, including negative exponents.

The Runtime Theory Team1 min read
Taught inBase cases and recursion treesPro — members onlyA recursive function needs a base case and a step that makes progress toward it. Drawing its calls as a tree tells you both its running time and its stack depth.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inx = 2.00000, n = 10

out1024.00000

inx = 2.10000, n = 3

out9.26100

inx = 2.00000, n = -2

out0.25000

Implement pow(x, n), which returns x raised to the integer power n. n can be negative and as large in magnitude as 2³¹.

Before you code

Multiplying n times is far too slow for n near 2 billion. Halve the exponent instead: x¹⁰ is (x⁵)², and x⁵ is x × (x²)².

Hints

  1. Base case: n == 0 returns 1.
  2. Compute the half power once, store it, and square it. Calling the function twice on n // 2 makes the tree branch and loses the speedup.
  3. For negative n, compute the power for −n and take the reciprocal. Careful: in 32-bit languages, −(−2³¹) overflows; convert to a 64-bit integer first.
  4. The iterative version reads the bits of n: square x for each bit, and multiply it into the result when the bit is 1.

Production & complexity notes

When solving Pow(x, n) on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Base cases and recursion trees to reinforce the underlying pattern.

What it practices

The difference between a chain and a branching recursion tree, from Base cases and recursion trees.

Not started

Sign in to save your learning progress.

Sign in to save