DSA interview question
A memory allocator only accepts block sizes that are powers of two (1, 2, 4, 8, …), because it splits and merges blocks by halving and doubling. Every allocation request must be validated instantly. A power of two has exactly one set bit, and subtracting 1 flips that bit off and turns every lower bit on, so n & (n − 1) is zero exactly for powers of two. Zero and negative numbers must be rejected separately.
Example: 16 → true; 3 → false; 0 → false.
bool isPowerOfTwo(int n);
| Input | Output | Explanation |
|---|---|---|
1 | true | 2⁰ |
16 | true | 10000 |
3 | false | 11 has two set bits |
0 | false | No set bits |
-16 | false | Negative numbers are never powers of two |
1073741824 | true | 2³⁰, the largest in a 32-bit int |
(Confirm: n is a 32-bit signed integer; only positive powers of two, 2⁰ to 2³⁰, return true.)
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