← Snap Interview InsightsSoftware Engineer
I knew this one but still fumbled the explanation a bit.
Start by clarifying edge cases (e.g., n <= 0) and then present a bitwise solution: a power of two has exactly one bit set, so n > 0 and (n & (n - 1)) == 0. If time permits, mention alternative approaches like loop division and compare their trade-offs.
Pro tip: Snapchat values efficient, clean code—lead with the O(1) bitwise solution and explicitly handle n <= 0, as many candidates forget negative numbers and zero. Also, briefly explain why the bit trick works (single set bit) to show depth.
Ask whether n can be negative or zero, and confirm the expected return type (boolean). State that 1 is a power of two (2^0) and that 0 and negatives are not.
Explain that a power of two in binary has exactly one '1' bit. Therefore, n > 0 and (n & (n - 1)) == 0 is a necessary and sufficient condition.
Test with n = 1 (true), n = 16 (true), n = 0 (false), n = -8 (false), and n = 6 (false) to demonstrate correctness and edge-case handling.
State that the bitwise method runs in O(1) time and O(1) space. Mention that a loop dividing by 2 repeatedly is O(log n) and less efficient, but could be a fallback if bitwise is not allowed.
Implement the function succinctly, e.g., 'return n > 0 && (n & (n - 1)) == 0;'. Verbally confirm it handles all edge cases and invite feedback.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.