Pow(x, n) (LeetCode 50)
Write your own version of pow(x, n) -- the function that raises a base x to an exponent n, i.e. produces x^n.
Negative exponents must work too: x^(-n) means 1 / x^n.
Worked Examples
x = 2.00000, n = 101024.00000210 = 1024.x = 2.10000, n = 39.261002.13 = 9.261.x = 2.00000, n = -20.25000⚖️Formal Constraints & Bounds
-100.0 < x < 100.0-231 <= n <= 231 - 1nis an integer.Either
xis not zero, orn > 0.-104 <= x^n <= 104
Core Insight
Linear multiplication O(N) times out for n = 2^31 - 1. By squaring the base and halving the exponent at each step, binary exponentiation calculates x^n in O(log N) iterations.
Real-World Scenario & Production Applications
Cryptographic RSA key exponentiation, modular exponentiation in Diffie-Hellman handshakes, 3D physics rendering scaling matrices.
Step-by-Step Execution Trace Table
| Step | Exponent n | Exponent Parity | Current Base x | Action Taken | Accumulated result |
|---|---|---|---|---|---|
| 1 | 10 | Even | 2.0 | Square base: x = 4.0, n = 5 | 1.0 |
| 2 | 5 | Odd | 4.0 | Multiply result: res *= 4.0 = 4.0, n = 4 | 4.0 |
| 3 | 4 | Even | 4.0 | Square base: x = 16.0, n = 2 | 4.0 |
| 4 | 2 | Even | 16.0 | Square base: x = 256.0, n = 1 | 4.0 |
| 5 | 1 | Odd | 256.0 | Multiply result: res *= 256.0 = 1024.0, n = 0 | 1024.0 (Done) |
The Math, Step by Step
1. The exponent written in binary
Write the exponent in binary, as a sum of powers of two. For example, , which is 1010 in binary. The powers of follow the same split, because exponents add when powers multiply:
In general, if bit of is (0 or 1), then
So is the product of the powers that belong to the set bits of . The code multiplies exactly these powers into result.
2. One round of the loop
Each round looks at the lowest bit of and then removes it:
| Line | Math | Effect |
|---|---|---|
if n % 2 == 1: | the lowest remaining bit is set | |
result *= curr_product | multiply by | this power belongs to |
curr_product *= curr_product | prepares the power for the next bit | |
n //= 2 | shift the bits right by one | the next bit becomes the lowest |
At the start of round (counting from 0), curr_product holds . It starts as , and each round squares it.
3. Why the result is right, and why it is fast
After the round for bit , result holds the product of over the set bits . When reaches 0, every bit has been handled, so result holds by the formula of part 1.
Each round uses the rule . When the lowest bit is 1, result takes one factor of curr_product. Then curr_product is squared and n is halved. A recursive version uses instead, which squares the answer of the half-size problem. Both make multiplications.
has about bits, and each round does at most two multiplications. So the code makes multiplications instead of the of multiplying by itself again and again. For that is 31 rounds instead of more than two billion multiplications.
4. Negative exponents
For , the rule is . The code replaces x with 1.0 / x and n with -n, and then runs the same loop on a positive exponent. The problem guarantees that is not zero when , so 1.0 / x never divides by zero.
The smallest allowed exponent is . Then -n is , which is one more than the largest 32-bit integer. Python integers have no fixed size, so n = -n works. In a language with 32-bit integers, this negation overflows. There the code must store in a 64-bit integer.
For example, and become and . The loop then computes .
5. Example 1 by hand
x = 2.0, n = 10, which is 1010 in binary.
| Round | n at the start | Lowest bit | result after the round | curr_product after squaring |
|---|---|---|---|---|
| 0 | 10 (1010) | 0 | ||
| 1 | 5 (101) | 1 | ||
| 2 | 2 (10) | 0 | ||
| 3 | 1 (1) | 1 |
The set bits are bits 1 and 3, so result is . The code returns 1024.0, the expected output 1024.00000. The last squaring, 65536, is computed but not used.
6. Example 2 by hand
x = 2.1, n = 3, which is 11 in binary. In round 0 the lowest bit is 1, so result becomes , and curr_product becomes . In round 1 the lowest bit is 1 again, so result becomes .
The exact value is . The number 2.1 has no exact binary form, so the float result is 9.261000000000001. It differs from the exact value 9.261 by about . Rounded to five decimal places it is 9.26100, the expected output.
7. From the formula to the code
| Math | In myPow |
|---|---|
| for | x = 1.0 / x and n = -n |
| the empty product is 1 | result = 1.0 |
curr_product = x | |
| bit | if n % 2 == 1: |
| multiply in | result *= curr_product |
curr_product *= curr_product | |
| next bit | n //= 2 |
The loop runs once per bit of , so the code takes time and space.
| 1 | if n < 0: |
| 2 | x = 1.0 / x |
| 3 | n = -n |
| 4 | result = 1.0 |
| 5 | curr_product = x |
| 6 | while n > 0: |
| 7 | if n % 2 == 1: |
| 8 | result *= curr_product |
| 9 | curr_product *= curr_product |
| 10 | n //= 2 |
| 11 | return result |
Conceptual Narrative
🧭 Conceptual Foundation & Pattern Intuition
Multiplying x by itself n times is the obvious solution — and also the slow one. This trick gets the same answer in a fraction of the multiplications by never solving a bigger problem than it has to.
📄 The Analogy: Folding Paper to Double Its Thickness
If you want a stack of paper 2^10 sheets thick, you don't stack sheets one at a time 1,024 times — you fold the stack in half, doubling its thickness, and repeat. 10 folds gets you 1,024 sheets in 10 moves, not 1,024. curr_product *= curr_product is exactly one "fold": it doubles the exponent you have computed, with one multiplication.
The only complication is when n is odd — you can't fold an odd stack perfectly in half, so you set one sheet aside first (multiply it into your running answer result), then fold the rest.
🔑 The Key Idea in the Code
Every bit of n's binary representation gets read exactly once (n //= 2), and each bit either says "fold only" (bit is 0) or "set a sheet aside, then fold" (bit is 1) — which is precisely how binary numbers decompose a power into a sum of powers of two.
Linear multiplication causing TLE: Multiplying by itself times takes operations, which times out when . Binary exponentiation (squaring and halving ) computes in .
Negative exponent handling: When , . Invert and negate .
32-bit signed integer underflow on : In C++ and Java, negating overflows
intbecauseINT_MAXis . Cast to a 64-bit integer (long long) before negating.
4-Phase Thought Process Model
Pattern Recognition Signals
The 10-second spot
"Implement pow(x, n)" with -231 <= n <= 231 - 1: the exponent can be about two billion and negative, so multiplying x in n times is far too slow.
Formulating the Predicate & Invariants
Turning intuition into a boolean rule
Invariant: before each round, result * curr_product ** n equals the original x ** n. Decision per round: if n % 2 == 1, result *= curr_product; then curr_product *= curr_product and n //= 2.
Silent Failure Traps & Edge Cases
Where confident candidates still lose points
Negative
n: flip once before the loop (x = 1.0 / x,n = -n); in Java or C++ copyninto a 64-bit variable first, since-(-231)overflows.Multiplying
xinntimes isO(N):n = 231 - 1means about two billion multiplications.Halve with
n //= 2, notn = n / 2: the float never lands on an exact bit pattern, somy_pow(2, 5)runs over 1,000 rounds and returns 2.0 instead of 32.
The 60-Second Interview Pitch
Say this out loud before you type a single line
I use Fast Power. I read
nin binary:x^13isx^8 · x^4 · x^1, and each of those powers is the square of the one before. First, a negativen: I flip it once withx = 1 / xandn = -n, copyingninto 64 bits in Java or C++ because-noverflows for minus two to the thirty-one. Then I keepresult = 1.0andcurr_product = x. Whilen > 0: ifn % 2 == 1,result *= curr_product; then I squarecurr_productand halvenwithn //= 2. It is correct becauseresulttimescurr_productto the powernalways equals the originalx ** n, and the loop stops atn = 0, soresultis the answer. There are at most 32 rounds, soO(log N)time andO(1)space.
Complexity & Mathematical Proof
O(log N)
Look at the loop: each round does one squaring (curr_product *= curr_product), at most one more multiplication (result *= curr_product when n % 2 == 1), and halves n with n //= 2. So the loop runs floor(log2 N) + 1 rounds, at most 32 for a 32-bit exponent, with at most two multiplications per round: O(log N) time and O(1) space.
O(1)
Look at memory allocations: the loop is iterative, so the call stack stays O(1). Only two numbers are kept, result and curr_product.
T(N) = ⌊ log2 |N| ⌋ + 1 = O(log N)
Derivation Progression
n //= 2, curr_product = curr_product · curr_product
Squares curr_product and halves n: O(1) work per bit of n.
if n \% 2 == 1: result ·= curr_product
Multiplies curr_product into result only on a 1 bit.
≤ 32 rounds for 32-bit N, ≤ 2 multiplications each
At most 32 rounds of at most two multiplications: n = 2^31 - 1 takes 62 multiplications, n = 2^31 takes 33.
Variable Definitions
Exponent power (at most 32 bits for signed 32-bit integer)
Memory Architecture & Bounds
O(1) Iterative (or O(log N) recursive)
O(1) Float registers
O(1) Computed float result
Boundary Best / Worst Cases
for n in {0, 1}.
.
for arbitrary n up to 2^31 - 1.
Pointer Invariant Transition Progression
Senior SWE Deconstruction & Hardware Caveats
Keywords: "calculate x raised to the power n". Naive linear multiplication requires steps, which will time out because . A Senior SWE recognizes Binary Exponentiation (Fast Power): decomposing exponent into binary powers using divide-and-conquer in time.
, . Time budget must be strictly logarithmic ( iterations).
With a modulus such as , reduce after every multiplication: one product of two reduced values stays below and fits in 64 bits, but a product of three does not. Floating-point result loses precision for large ; LeetCode accepts a small error, but exact answers need integers and a modulus.
Core Algorithmic State Invariants
- Same Loop, Other Products
The loop only needs a multiplication that can be grouped in any order, so it also raises a 2 x 2 matrix to the n-th power (the n-th Fibonacci number in O(log n) matrix products) and works modulo 10^9 + 7 when every multiplication is reduced at once.
Pow(x, n) (LeetCode 50)
Write your own version of pow(x, n) -- the function that raises a base x to an exponent n, i.e. produces x^n.
Negative exponents must work too: x^(-n) means 1 / x^n.
Worked Examples
x = 2.00000, n = 101024.00000210 = 1024.x = 2.10000, n = 39.261002.13 = 9.261.x = 2.00000, n = -20.25000⚖️Formal Constraints & Bounds
-100.0 < x < 100.0-231 <= n <= 231 - 1nis an integer.Either
xis not zero, orn > 0.-104 <= x^n <= 104
Core Insight
Linear multiplication O(N) times out for n = 2^31 - 1. By squaring the base and halving the exponent at each step, binary exponentiation calculates x^n in O(log N) iterations.
Real-World Scenario & Production Applications
Cryptographic RSA key exponentiation, modular exponentiation in Diffie-Hellman handshakes, 3D physics rendering scaling matrices.
Step-by-Step Execution Trace Table
| Step | Exponent n | Exponent Parity | Current Base x | Action Taken | Accumulated result |
|---|---|---|---|---|---|
| 1 | 10 | Even | 2.0 | Square base: x = 4.0, n = 5 | 1.0 |
| 2 | 5 | Odd | 4.0 | Multiply result: res *= 4.0 = 4.0, n = 4 | 4.0 |
| 3 | 4 | Even | 4.0 | Square base: x = 16.0, n = 2 | 4.0 |
| 4 | 2 | Even | 16.0 | Square base: x = 256.0, n = 1 | 4.0 |
| 5 | 1 | Odd | 256.0 | Multiply result: res *= 256.0 = 1024.0, n = 0 | 1024.0 (Done) |
The Math, Step by Step
1. The exponent written in binary
Write the exponent in binary, as a sum of powers of two. For example, , which is 1010 in binary. The powers of follow the same split, because exponents add when powers multiply:
In general, if bit of is (0 or 1), then
So is the product of the powers that belong to the set bits of . The code multiplies exactly these powers into result.
2. One round of the loop
Each round looks at the lowest bit of and then removes it:
| Line | Math | Effect |
|---|---|---|
if n % 2 == 1: | the lowest remaining bit is set | |
result *= curr_product | multiply by | this power belongs to |
curr_product *= curr_product | prepares the power for the next bit | |
n //= 2 | shift the bits right by one | the next bit becomes the lowest |
At the start of round (counting from 0), curr_product holds . It starts as , and each round squares it.
3. Why the result is right, and why it is fast
After the round for bit , result holds the product of over the set bits . When reaches 0, every bit has been handled, so result holds by the formula of part 1.
Each round uses the rule . When the lowest bit is 1, result takes one factor of curr_product. Then curr_product is squared and n is halved. A recursive version uses instead, which squares the answer of the half-size problem. Both make multiplications.
has about bits, and each round does at most two multiplications. So the code makes multiplications instead of the of multiplying by itself again and again. For that is 31 rounds instead of more than two billion multiplications.
4. Negative exponents
For , the rule is . The code replaces x with 1.0 / x and n with -n, and then runs the same loop on a positive exponent. The problem guarantees that is not zero when , so 1.0 / x never divides by zero.
The smallest allowed exponent is . Then -n is , which is one more than the largest 32-bit integer. Python integers have no fixed size, so n = -n works. In a language with 32-bit integers, this negation overflows. There the code must store in a 64-bit integer.
For example, and become and . The loop then computes .
5. Example 1 by hand
x = 2.0, n = 10, which is 1010 in binary.
| Round | n at the start | Lowest bit | result after the round | curr_product after squaring |
|---|---|---|---|---|
| 0 | 10 (1010) | 0 | ||
| 1 | 5 (101) | 1 | ||
| 2 | 2 (10) | 0 | ||
| 3 | 1 (1) | 1 |
The set bits are bits 1 and 3, so result is . The code returns 1024.0, the expected output 1024.00000. The last squaring, 65536, is computed but not used.
6. Example 2 by hand
x = 2.1, n = 3, which is 11 in binary. In round 0 the lowest bit is 1, so result becomes , and curr_product becomes . In round 1 the lowest bit is 1 again, so result becomes .
The exact value is . The number 2.1 has no exact binary form, so the float result is 9.261000000000001. It differs from the exact value 9.261 by about . Rounded to five decimal places it is 9.26100, the expected output.
7. From the formula to the code
| Math | In myPow |
|---|---|
| for | x = 1.0 / x and n = -n |
| the empty product is 1 | result = 1.0 |
curr_product = x | |
| bit | if n % 2 == 1: |
| multiply in | result *= curr_product |
curr_product *= curr_product | |
| next bit | n //= 2 |
The loop runs once per bit of , so the code takes time and space.
| 1 | if n < 0: |
| 2 | x = 1.0 / x |
| 3 | n = -n |
| 4 | result = 1.0 |
| 5 | curr_product = x |
| 6 | while n > 0: |
| 7 | if n % 2 == 1: |
| 8 | result *= curr_product |
| 9 | curr_product *= curr_product |
| 10 | n //= 2 |
| 11 | return result |
Conceptual Narrative
🧭 Conceptual Foundation & Pattern Intuition
Multiplying x by itself n times is the obvious solution — and also the slow one. This trick gets the same answer in a fraction of the multiplications by never solving a bigger problem than it has to.
📄 The Analogy: Folding Paper to Double Its Thickness
If you want a stack of paper 2^10 sheets thick, you don't stack sheets one at a time 1,024 times — you fold the stack in half, doubling its thickness, and repeat. 10 folds gets you 1,024 sheets in 10 moves, not 1,024. curr_product *= curr_product is exactly one "fold": it doubles the exponent you have computed, with one multiplication.
The only complication is when n is odd — you can't fold an odd stack perfectly in half, so you set one sheet aside first (multiply it into your running answer result), then fold the rest.
🔑 The Key Idea in the Code
Every bit of n's binary representation gets read exactly once (n //= 2), and each bit either says "fold only" (bit is 0) or "set a sheet aside, then fold" (bit is 1) — which is precisely how binary numbers decompose a power into a sum of powers of two.
Linear multiplication causing TLE: Multiplying by itself times takes operations, which times out when . Binary exponentiation (squaring and halving ) computes in .
Negative exponent handling: When , . Invert and negate .
32-bit signed integer underflow on : In C++ and Java, negating overflows
intbecauseINT_MAXis . Cast to a 64-bit integer (long long) before negating.
4-Phase Thought Process Model
Pattern Recognition Signals
The 10-second spot
"Implement pow(x, n)" with -231 <= n <= 231 - 1: the exponent can be about two billion and negative, so multiplying x in n times is far too slow.
Formulating the Predicate & Invariants
Turning intuition into a boolean rule
Invariant: before each round, result * curr_product ** n equals the original x ** n. Decision per round: if n % 2 == 1, result *= curr_product; then curr_product *= curr_product and n //= 2.
Silent Failure Traps & Edge Cases
Where confident candidates still lose points
Negative
n: flip once before the loop (x = 1.0 / x,n = -n); in Java or C++ copyninto a 64-bit variable first, since-(-231)overflows.Multiplying
xinntimes isO(N):n = 231 - 1means about two billion multiplications.Halve with
n //= 2, notn = n / 2: the float never lands on an exact bit pattern, somy_pow(2, 5)runs over 1,000 rounds and returns 2.0 instead of 32.
The 60-Second Interview Pitch
Say this out loud before you type a single line
I use Fast Power. I read
nin binary:x^13isx^8 · x^4 · x^1, and each of those powers is the square of the one before. First, a negativen: I flip it once withx = 1 / xandn = -n, copyingninto 64 bits in Java or C++ because-noverflows for minus two to the thirty-one. Then I keepresult = 1.0andcurr_product = x. Whilen > 0: ifn % 2 == 1,result *= curr_product; then I squarecurr_productand halvenwithn //= 2. It is correct becauseresulttimescurr_productto the powernalways equals the originalx ** n, and the loop stops atn = 0, soresultis the answer. There are at most 32 rounds, soO(log N)time andO(1)space.
Complexity & Mathematical Proof
O(log N)
Look at the loop: each round does one squaring (curr_product *= curr_product), at most one more multiplication (result *= curr_product when n % 2 == 1), and halves n with n //= 2. So the loop runs floor(log2 N) + 1 rounds, at most 32 for a 32-bit exponent, with at most two multiplications per round: O(log N) time and O(1) space.
O(1)
Look at memory allocations: the loop is iterative, so the call stack stays O(1). Only two numbers are kept, result and curr_product.
T(N) = ⌊ log2 |N| ⌋ + 1 = O(log N)
Derivation Progression
n //= 2, curr_product = curr_product · curr_product
Squares curr_product and halves n: O(1) work per bit of n.
if n \% 2 == 1: result ·= curr_product
Multiplies curr_product into result only on a 1 bit.
≤ 32 rounds for 32-bit N, ≤ 2 multiplications each
At most 32 rounds of at most two multiplications: n = 2^31 - 1 takes 62 multiplications, n = 2^31 takes 33.
Variable Definitions
Exponent power (at most 32 bits for signed 32-bit integer)
Memory Architecture & Bounds
O(1) Iterative (or O(log N) recursive)
O(1) Float registers
O(1) Computed float result
Boundary Best / Worst Cases
for n in {0, 1}.
.
for arbitrary n up to 2^31 - 1.
Pointer Invariant Transition Progression
Senior SWE Deconstruction & Hardware Caveats
Keywords: "calculate x raised to the power n". Naive linear multiplication requires steps, which will time out because . A Senior SWE recognizes Binary Exponentiation (Fast Power): decomposing exponent into binary powers using divide-and-conquer in time.
, . Time budget must be strictly logarithmic ( iterations).
With a modulus such as , reduce after every multiplication: one product of two reduced values stays below and fits in 64 bits, but a product of three does not. Floating-point result loses precision for large ; LeetCode accepts a small error, but exact answers need integers and a modulus.
Core Algorithmic State Invariants
- Same Loop, Other Products
The loop only needs a multiplication that can be grouped in any order, so it also raises a 2 x 2 matrix to the n-th power (the n-th Fibonacci number in O(log n) matrix products) and works modulo 10^9 + 7 when every multiplication is reduced at once.