Bitwise Idioms and Their Preconditions
Follow the changed bits and check the assumptions under which each shortcut is valid.
Core Intuition & How It Works
Classic bitwise idioms exploit two’s-complement arithmetic: x & (x - 1) clears the lowest set bit, x & -x isolates it, and XOR cancels duplicate pairs. Each idiom requires verifying preconditions like non-negativity or signedness.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(1) or O(popcount) |
| Space Complexity | O(1) |
| Topic Chapter | Chapter 15: Bit Manipulation |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Power-of-two test: x > 0 && (x & (x - 1)) === 0. Single unique number among pairs: XOR all elements together.
Common Pitfalls & Edge Cases
Omitting x > 0 in the power-of-two check (which falsely accepts 0) or ignoring signed overflow on -INT_MIN.
Real-World & Technical Interview Applications
Fenwick trees (x & -x), Brian Kernighan popcount, single-number problems, and low-level graphics/systems code.