Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Math & Geometry
MediumLC 50

Pow(x, n) (LeetCode 50)

Target Frequency:GoogleAmazonMicrosoft

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

Example 1
Input:x = 2.00000, n = 10
Output:1024.00000
Explanation: 210 = 1024.
Example 2
Input:x = 2.10000, n = 3
Output:9.26100
Explanation: 2.13 = 9.261.
Example 3
Input:x = 2.00000, n = -2
Output:0.25000
Explanation: 2^-2 = 1/(2^2) = 1/4 = 0.25

⚖️Formal Constraints & Bounds

  • -100.0 < x < 100.0

  • -231 <= n <= 231 - 1

  • n is an integer.

  • Either x is not zero, or n > 0.

  • -104 <= x^n <= 104

Deep-Dive & Conceptual Insights

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

StepExponent nExponent ParityCurrent Base xAction TakenAccumulated result
110Even2.0Square base: x = 4.0, n = 51.0
25Odd4.0Multiply result: res *= 4.0 = 4.0, n = 44.0
34Even4.0Square base: x = 16.0, n = 24.0
42Even16.0Square base: x = 256.0, n = 14.0
51Odd256.0Multiply result: res *= 256.0 = 1024.0, n = 01024.0 (Done)
Worked on Paper

The Math, Step by Step

1. The exponent written in binary

Write the exponent nnn in binary, as a sum of powers of two. For example, 10=8+2=23+2110 = 8 + 2 = 2^3 + 2^110=8+2=23+21, which is 1010 in binary. The powers of xxx follow the same split, because exponents add when powers multiply:

x10=x8+2=x8⋅x2x^{10} = x^{8 + 2} = x^{8} \cdot x^{2}x10=x8+2=x8⋅x2

In general, if bit iii of nnn is bib_ibi​ (0 or 1), then

xn=∏i : bi=1x2ix^n = \prod_{i\,:\, b_i = 1} x^{2^i}xn=∏i:bi​=1​x2i

So xnx^nxn is the product of the powers x1,x2,x4,x8,…x^1, x^2, x^4, x^8, \ldotsx1,x2,x4,x8,… that belong to the set bits of nnn. The code multiplies exactly these powers into result.

2. One round of the loop

Each round looks at the lowest bit of nnn and then removes it:

LineMathEffect
if n % 2 == 1:bi=1b_i = 1bi​=1the lowest remaining bit is set
result *= curr_productmultiply by x2ix^{2^i}x2ithis power belongs to xnx^nxn
curr_product *= curr_productx2i⋅x2i=x2i+1x^{2^i} \cdot x^{2^i} = x^{2^{i+1}}x2i⋅x2i=x2i+1prepares the power for the next bit
n //= 2shift the bits right by onethe next bit becomes the lowest

At the start of round iii (counting from 0), curr_product holds x2ix^{2^i}x2i. It starts as x=x20x = x^{2^0}x=x20, and each round squares it.

3. Why the result is right, and why it is fast

After the round for bit iii, result holds the product of x2jx^{2^j}x2j over the set bits j≤ij \le ij≤i. When nnn reaches 0, every bit has been handled, so result holds xnx^nxn by the formula of part 1.

Each round uses the rule xn=(x2)⌊n/2⌋⋅x n mod 2x^n = (x^2)^{\lfloor n/2 \rfloor} \cdot x^{\,n \bmod 2}xn=(x2)⌊n/2⌋⋅xnmod2. 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 xn=(x⌊n/2⌋)2⋅x n mod 2x^n = (x^{\lfloor n/2 \rfloor})^2 \cdot x^{\,n \bmod 2}xn=(x⌊n/2⌋)2⋅xnmod2 instead, which squares the answer of the half-size problem. Both make O(log⁡n)O(\log n)O(logn) multiplications.

nnn has about log⁡2n+1\log_2 n + 1log2​n+1 bits, and each round does at most two multiplications. So the code makes O(log⁡n)O(\log n)O(logn) multiplications instead of the n−1n - 1n−1 of multiplying xxx by itself again and again. For n=231−1n = 2^{31} - 1n=231−1 that is 31 rounds instead of more than two billion multiplications.

4. Negative exponents

For n<0n < 0n<0, the rule is xn=(1x)−nx^{n} = \left(\frac{1}{x}\right)^{-n}xn=(x1​)−n. 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 xxx is not zero when n≤0n \le 0n≤0, so 1.0 / x never divides by zero.

The smallest allowed exponent is n=−231n = -2^{31}n=−231. Then -n is 2312^{31}231, 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 −n-n−n in a 64-bit integer.

For example, x=2x = 2x=2 and n=−2n = -2n=−2 become x=0.5x = 0.5x=0.5 and n=2n = 2n=2. The loop then computes 0.5⋅0.5=0.250.5 \cdot 0.5 = 0.250.5⋅0.5=0.25.

5. Example 1 by hand

x = 2.0, n = 10, which is 1010 in binary.

Round iiin at the startLowest bitresult after the roundcurr_product after squaring
010 (1010)011122=42^2 = 422=4
15 (101)11⋅4=41 \cdot 4 = 41⋅4=442=164^2 = 1642=16
22 (10)0444162=25616^2 = 256162=256
31 (1)14⋅256=10244 \cdot 256 = 10244⋅256=10242562=65536256^2 = 655362562=65536

The set bits are bits 1 and 3, so result is x2⋅x8=4⋅256=1024x^{2} \cdot x^{8} = 4 \cdot 256 = 1024x2⋅x8=4⋅256=1024. 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 2.12.12.1, and curr_product becomes 2.12=4.412.1^2 = 4.412.12=4.41. In round 1 the lowest bit is 1 again, so result becomes 2.1⋅4.412.1 \cdot 4.412.1⋅4.41.

The exact value is 2.13=92611000=9.2612.1^3 = \frac{9261}{1000} = 9.2612.13=10009261​=9.261. 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 1.0⋅10−151.0 \cdot 10^{-15}1.0⋅10−15. Rounded to five decimal places it is 9.26100, the expected output.

7. From the formula to the code
MathIn myPow
xn=(1/x)−nx^{n} = (1/x)^{-n}xn=(1/x)−n for n<0n < 0n<0x = 1.0 / x and n = -n
the empty product is 1result = 1.0
x20=xx^{2^0} = xx20=xcurr_product = x
bit bi=1b_i = 1bi​=1if n % 2 == 1:
multiply in x2ix^{2^i}x2iresult *= curr_product
x2i+1=(x2i)2x^{2^{i+1}} = (x^{2^i})^2x2i+1=(x2i)2curr_product *= curr_product
next bitn //= 2

The loop runs once per bit of nnn, so the code takes O(log⁡n)O(\log n)O(logn) time and O(1)O(1)O(1) space.

Code Shape
Archetype Code Shape
Python
1if n < 0:
2 x = 1.0 / x
3 n = -n
4result = 1.0
5curr_product = x
6while n > 0:
7 if n % 2 == 1:
8 result *= curr_product
9 curr_product *= curr_product
10 n //= 2
11return 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 O(N)O(N)O(N) multiplication causing TLE: Multiplying xxx by itself nnn times takes O(N)O(N)O(N) operations, which times out when n=2⋅109n = 2 \cdot 10^9n=2⋅109. Binary exponentiation (squaring xxx and halving nnn) computes xnx^nxn in O(log⁡N)O(\log N)O(logN).

  • Negative exponent handling: When n<0n < 0n<0, xn=(1/x)−nx^n = (1/x)^{-n}xn=(1/x)−n. Invert x=1/xx = 1 / xx=1/x and negate n=−nn = -nn=−n.

  • 32-bit signed integer underflow on n=−231n = -2^{31}n=−231: In C++ and Java, negating −2147483648-2147483648−2147483648 overflows int because INT_MAX is 214748364721474836472147483647. Cast nnn to a 64-bit integer (long long) before negating.

Senior SWE Reasoning Architecture

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++ copy n into a 64-bit variable first, since -(-231) overflows.

  • Multiplying x in n times is O(N): n = 231 - 1 means about two billion multiplications.

  • Halve with n //= 2, not n = n / 2: the float never lands on an exact bit pattern, so my_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 n in binary: x^13 is x^8 · x^4 · x^1, and each of those powers is the square of the one before. First, a negative n: I flip it once with x = 1 / x and n = -n, copying n into 64 bits in Java or C++ because -n overflows for minus two to the thirty-one. Then I keep result = 1.0 and curr_product = x. While n > 0: if n % 2 == 1, result *= curr_product; then I square curr_product and halve n with n //= 2. It is correct because result times curr_product to the power n always equals the original x ** n, and the loop stops at n = 0, so result is the answer. There are at most 32 rounds, so O(log N) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

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.

SPACE COMPLEXITY

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.

Formal Recurrence Relation

T(N) = ⌊ log2 |N| ⌋ + 1 = O(log N)

Derivation Progression

Binary Exponent Halving

n //= 2, curr_product = curr_product · curr_product

Squares curr_product and halves n: O(1) work per bit of n.

Odd Exponent Accumulation

if n \% 2 == 1: result ·= curr_product

Multiplies curr_product into result only on a 1 bit.

Logarithmic Steps

≤ 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

NNN

Exponent power (at most 32 bits for signed 32-bit integer)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative (or O(log N) recursive)

🔵 Auxiliary Heap

O(1) Float registers

🟢 Output Space

O(1) Computed float result

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) for n in {0, 1}.

Average Case

O(log⁡N)O(\log N)O(logN).

Worst Case

O(log⁡N)O(\log N)O(logN) for arbitrary n up to 2^31 - 1.

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Keywords: "calculate x raised to the power n". Naive linear multiplication x×x×…x \times x \times \dotsx×x×… requires O(n)O(n)O(n) steps, which will time out because n≈2×109n \approx 2 \times 10^9n≈2×109. A Senior SWE recognizes Binary Exponentiation (Fast Power): decomposing exponent nnn into binary powers using divide-and-conquer xn=(x2)n/2x^n = (x^2)^{n/2}xn=(x2)n/2 in O(log⁡n)O(\log n)O(logn) time.

CONSTRAINTS & BOUNDS

−100.0<x<100.0-100.0 < x < 100.0−100.0<x<100.0, −231≤n≤231−1-2^{31} \le n \le 2^{31} - 1−231≤n≤231−1. Time budget must be strictly logarithmic (O(log⁡n)≤32O(\log n) \le 32O(logn)≤32 iterations).

FAANG PRODUCTION TRAPS & EDGE CASES

With a modulus such as 109+710^9 + 7109+7, reduce after every multiplication: one product of two reduced values stays below 101810^{18}1018 and fits in 64 bits, but a product of three does not. Floating-point result loses precision for large nnn; LeetCode accepts a small error, but exact answers need integers and a modulus.

Core Algorithmic State Invariants

  1. 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.

Theory Context•Math & Geometry
MediumLC 50

Pow(x, n) (LeetCode 50)

Target Frequency:GoogleAmazonMicrosoft

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

Example 1
Input:x = 2.00000, n = 10
Output:1024.00000
Explanation: 210 = 1024.
Example 2
Input:x = 2.10000, n = 3
Output:9.26100
Explanation: 2.13 = 9.261.
Example 3
Input:x = 2.00000, n = -2
Output:0.25000
Explanation: 2^-2 = 1/(2^2) = 1/4 = 0.25

⚖️Formal Constraints & Bounds

  • -100.0 < x < 100.0

  • -231 <= n <= 231 - 1

  • n is an integer.

  • Either x is not zero, or n > 0.

  • -104 <= x^n <= 104

Deep-Dive & Conceptual Insights

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

StepExponent nExponent ParityCurrent Base xAction TakenAccumulated result
110Even2.0Square base: x = 4.0, n = 51.0
25Odd4.0Multiply result: res *= 4.0 = 4.0, n = 44.0
34Even4.0Square base: x = 16.0, n = 24.0
42Even16.0Square base: x = 256.0, n = 14.0
51Odd256.0Multiply result: res *= 256.0 = 1024.0, n = 01024.0 (Done)
Worked on Paper

The Math, Step by Step

1. The exponent written in binary

Write the exponent nnn in binary, as a sum of powers of two. For example, 10=8+2=23+2110 = 8 + 2 = 2^3 + 2^110=8+2=23+21, which is 1010 in binary. The powers of xxx follow the same split, because exponents add when powers multiply:

x10=x8+2=x8⋅x2x^{10} = x^{8 + 2} = x^{8} \cdot x^{2}x10=x8+2=x8⋅x2

In general, if bit iii of nnn is bib_ibi​ (0 or 1), then

xn=∏i : bi=1x2ix^n = \prod_{i\,:\, b_i = 1} x^{2^i}xn=∏i:bi​=1​x2i

So xnx^nxn is the product of the powers x1,x2,x4,x8,…x^1, x^2, x^4, x^8, \ldotsx1,x2,x4,x8,… that belong to the set bits of nnn. The code multiplies exactly these powers into result.

2. One round of the loop

Each round looks at the lowest bit of nnn and then removes it:

LineMathEffect
if n % 2 == 1:bi=1b_i = 1bi​=1the lowest remaining bit is set
result *= curr_productmultiply by x2ix^{2^i}x2ithis power belongs to xnx^nxn
curr_product *= curr_productx2i⋅x2i=x2i+1x^{2^i} \cdot x^{2^i} = x^{2^{i+1}}x2i⋅x2i=x2i+1prepares the power for the next bit
n //= 2shift the bits right by onethe next bit becomes the lowest

At the start of round iii (counting from 0), curr_product holds x2ix^{2^i}x2i. It starts as x=x20x = x^{2^0}x=x20, and each round squares it.

3. Why the result is right, and why it is fast

After the round for bit iii, result holds the product of x2jx^{2^j}x2j over the set bits j≤ij \le ij≤i. When nnn reaches 0, every bit has been handled, so result holds xnx^nxn by the formula of part 1.

Each round uses the rule xn=(x2)⌊n/2⌋⋅x n mod 2x^n = (x^2)^{\lfloor n/2 \rfloor} \cdot x^{\,n \bmod 2}xn=(x2)⌊n/2⌋⋅xnmod2. 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 xn=(x⌊n/2⌋)2⋅x n mod 2x^n = (x^{\lfloor n/2 \rfloor})^2 \cdot x^{\,n \bmod 2}xn=(x⌊n/2⌋)2⋅xnmod2 instead, which squares the answer of the half-size problem. Both make O(log⁡n)O(\log n)O(logn) multiplications.

nnn has about log⁡2n+1\log_2 n + 1log2​n+1 bits, and each round does at most two multiplications. So the code makes O(log⁡n)O(\log n)O(logn) multiplications instead of the n−1n - 1n−1 of multiplying xxx by itself again and again. For n=231−1n = 2^{31} - 1n=231−1 that is 31 rounds instead of more than two billion multiplications.

4. Negative exponents

For n<0n < 0n<0, the rule is xn=(1x)−nx^{n} = \left(\frac{1}{x}\right)^{-n}xn=(x1​)−n. 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 xxx is not zero when n≤0n \le 0n≤0, so 1.0 / x never divides by zero.

The smallest allowed exponent is n=−231n = -2^{31}n=−231. Then -n is 2312^{31}231, 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 −n-n−n in a 64-bit integer.

For example, x=2x = 2x=2 and n=−2n = -2n=−2 become x=0.5x = 0.5x=0.5 and n=2n = 2n=2. The loop then computes 0.5⋅0.5=0.250.5 \cdot 0.5 = 0.250.5⋅0.5=0.25.

5. Example 1 by hand

x = 2.0, n = 10, which is 1010 in binary.

Round iiin at the startLowest bitresult after the roundcurr_product after squaring
010 (1010)011122=42^2 = 422=4
15 (101)11⋅4=41 \cdot 4 = 41⋅4=442=164^2 = 1642=16
22 (10)0444162=25616^2 = 256162=256
31 (1)14⋅256=10244 \cdot 256 = 10244⋅256=10242562=65536256^2 = 655362562=65536

The set bits are bits 1 and 3, so result is x2⋅x8=4⋅256=1024x^{2} \cdot x^{8} = 4 \cdot 256 = 1024x2⋅x8=4⋅256=1024. 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 2.12.12.1, and curr_product becomes 2.12=4.412.1^2 = 4.412.12=4.41. In round 1 the lowest bit is 1 again, so result becomes 2.1⋅4.412.1 \cdot 4.412.1⋅4.41.

The exact value is 2.13=92611000=9.2612.1^3 = \frac{9261}{1000} = 9.2612.13=10009261​=9.261. 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 1.0⋅10−151.0 \cdot 10^{-15}1.0⋅10−15. Rounded to five decimal places it is 9.26100, the expected output.

7. From the formula to the code
MathIn myPow
xn=(1/x)−nx^{n} = (1/x)^{-n}xn=(1/x)−n for n<0n < 0n<0x = 1.0 / x and n = -n
the empty product is 1result = 1.0
x20=xx^{2^0} = xx20=xcurr_product = x
bit bi=1b_i = 1bi​=1if n % 2 == 1:
multiply in x2ix^{2^i}x2iresult *= curr_product
x2i+1=(x2i)2x^{2^{i+1}} = (x^{2^i})^2x2i+1=(x2i)2curr_product *= curr_product
next bitn //= 2

The loop runs once per bit of nnn, so the code takes O(log⁡n)O(\log n)O(logn) time and O(1)O(1)O(1) space.

Code Shape
Archetype Code Shape
Python
1if n < 0:
2 x = 1.0 / x
3 n = -n
4result = 1.0
5curr_product = x
6while n > 0:
7 if n % 2 == 1:
8 result *= curr_product
9 curr_product *= curr_product
10 n //= 2
11return 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 O(N)O(N)O(N) multiplication causing TLE: Multiplying xxx by itself nnn times takes O(N)O(N)O(N) operations, which times out when n=2⋅109n = 2 \cdot 10^9n=2⋅109. Binary exponentiation (squaring xxx and halving nnn) computes xnx^nxn in O(log⁡N)O(\log N)O(logN).

  • Negative exponent handling: When n<0n < 0n<0, xn=(1/x)−nx^n = (1/x)^{-n}xn=(1/x)−n. Invert x=1/xx = 1 / xx=1/x and negate n=−nn = -nn=−n.

  • 32-bit signed integer underflow on n=−231n = -2^{31}n=−231: In C++ and Java, negating −2147483648-2147483648−2147483648 overflows int because INT_MAX is 214748364721474836472147483647. Cast nnn to a 64-bit integer (long long) before negating.

Senior SWE Reasoning Architecture

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++ copy n into a 64-bit variable first, since -(-231) overflows.

  • Multiplying x in n times is O(N): n = 231 - 1 means about two billion multiplications.

  • Halve with n //= 2, not n = n / 2: the float never lands on an exact bit pattern, so my_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 n in binary: x^13 is x^8 · x^4 · x^1, and each of those powers is the square of the one before. First, a negative n: I flip it once with x = 1 / x and n = -n, copying n into 64 bits in Java or C++ because -n overflows for minus two to the thirty-one. Then I keep result = 1.0 and curr_product = x. While n > 0: if n % 2 == 1, result *= curr_product; then I square curr_product and halve n with n //= 2. It is correct because result times curr_product to the power n always equals the original x ** n, and the loop stops at n = 0, so result is the answer. There are at most 32 rounds, so O(log N) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

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.

SPACE COMPLEXITY

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.

Formal Recurrence Relation

T(N) = ⌊ log2 |N| ⌋ + 1 = O(log N)

Derivation Progression

Binary Exponent Halving

n //= 2, curr_product = curr_product · curr_product

Squares curr_product and halves n: O(1) work per bit of n.

Odd Exponent Accumulation

if n \% 2 == 1: result ·= curr_product

Multiplies curr_product into result only on a 1 bit.

Logarithmic Steps

≤ 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

NNN

Exponent power (at most 32 bits for signed 32-bit integer)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative (or O(log N) recursive)

🔵 Auxiliary Heap

O(1) Float registers

🟢 Output Space

O(1) Computed float result

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) for n in {0, 1}.

Average Case

O(log⁡N)O(\log N)O(logN).

Worst Case

O(log⁡N)O(\log N)O(logN) for arbitrary n up to 2^31 - 1.

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Keywords: "calculate x raised to the power n". Naive linear multiplication x×x×…x \times x \times \dotsx×x×… requires O(n)O(n)O(n) steps, which will time out because n≈2×109n \approx 2 \times 10^9n≈2×109. A Senior SWE recognizes Binary Exponentiation (Fast Power): decomposing exponent nnn into binary powers using divide-and-conquer xn=(x2)n/2x^n = (x^2)^{n/2}xn=(x2)n/2 in O(log⁡n)O(\log n)O(logn) time.

CONSTRAINTS & BOUNDS

−100.0<x<100.0-100.0 < x < 100.0−100.0<x<100.0, −231≤n≤231−1-2^{31} \le n \le 2^{31} - 1−231≤n≤231−1. Time budget must be strictly logarithmic (O(log⁡n)≤32O(\log n) \le 32O(logn)≤32 iterations).

FAANG PRODUCTION TRAPS & EDGE CASES

With a modulus such as 109+710^9 + 7109+7, reduce after every multiplication: one product of two reduced values stays below 101810^{18}1018 and fits in 64 bits, but a product of three does not. Floating-point result loses precision for large nnn; LeetCode accepts a small error, but exact answers need integers and a modulus.

Core Algorithmic State Invariants

  1. 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.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•