DSA interview question
A physics engine evaluates x^n inside a hot loop millions of times per frame, so it needs the fastest, allocation-free version: no recursion. Binary exponentiation reads the bits of n from least to most significant while repeatedly squaring x: after k squarings, x holds x^(2^k), and it's multiplied into the result exactly when bit k of n is 1. Negative exponents use 1/x with a 64-bit exponent so n = INT_MIN is safe.
Example: x = 3, n = 5 (101 in binary) → 3^4 · 3^1 = 243.
double myPow(double x, int n);
Input (x, n) | Output | Explanation |
|---|---|---|
(2.00000, 10) | 1024.00000 | 10 = 1010: 2⁸ · 2² |
(2.10000, 3) | 9.26100 | |
(2.00000, -2) | 0.25000 | |
(3.00000, 5) | 243.00000 | 5 = 101: 3⁴ · 3¹ |
(-1.00000, -2147483648) | 1.00000 | Even exponent; negating INT_MIN needs 64 bits |
(0.00000, 5) | 0.00000 |
(Confirm: x ≠ 0 when n < 0; answers within 10⁻⁵ are accepted; O(log |n|) time and O(1) space.)
(a^b) mod m is the backbone of many number-theory problems.On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in