Bit Masks for Testing and Updating Bits
Identify the mask bit positions before applying a bitwise operation.
Core Intuition & How It Works
Bit masks pack boolean flags into a single integer and test, set, clear, or toggle individual bits in O(1) using bitwise AND (&), OR (|), XOR (^), and shifts (<<, >>).
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) per bitwise op |
| Space Complexity | O(1) |
| Topic Chapter | Chapter 15: Bit Manipulation |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Test bit k with (x & (1 << k)) !== 0, set with x | (1 << k), clear with x & ~(1 << k), and toggle with x ^ (1 << k).
Common Pitfalls & Edge Cases
Forgetting operator precedence (in most languages, == binds tighter than & or ^) or overflowing 32-bit signed shifts.
Real-World & Technical Interview Applications
Unix file permissions, feature flags, network subnet masks, and bitmask dynamic programming.