Raise a Number to an Integer Power in Logarithmic Time
Last updated: November 29, 2026
Quick Overview
Implement pow(x, n) for a floating-point base x and a 32-bit signed integer exponent n without using built-in power functions, running in O(log |n|) multiplications.
Meta
November 29, 20260
0
0 solved
Implement pow(x, n) for a floating-point base x and a 32-bit signed integer exponent n without using built-in power functions, running in O(log |n|) multiplications.
Fast exponentiation is a compact Meta screen question that tests whether you know binary exponentiation and can handle negative exponents and edge values. The same idea powers modular hashing and matrix exponentiation, which interviewers may bring up as follow-ups.
What the Interviewer Expects
- Uses repeated squaring over the bits of n
- Handles negative exponents by inverting the base
- Avoids overflow when negating the minimum 32-bit integer
- Prefers an iterative loop over deep recursion
- Explains O(log n) clearly
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Compute (a^b) mod m for huge b, as used in rolling hashes.
- Use the same idea to compute the n-th Fibonacci number in O(log n).
- How would floating-point error accumulate, and how would you bound it?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
x is a float, n is between -2^31 and 2^31 - 1. Return x^n as a float. Assume x is not 0 when n is negative. Target O(log |n|) time and O(1) space....
High-Level Design
Write n in binary. x^n is the product of x^(2^k) over every set bit k of n. Iterate: keep base which starts at x and is squared each step, and multiply it into result whenever the low bit of n is ...