Operate directly on binary representations. Ultra-fast, O(1) space tricks for states, counting, and powers of 2. Essential for advanced problem solving.
| Pattern | Trick | Use Case |
|---|---|---|
| Check ith bit | (n >> i) & 1 | Is the i-th flag set? |
| Set ith bit | n | (1 << i) | Turn on the i-th flag |
| Clear ith bit | n & ~(1 << i) | Turn off the i-th flag |
| Toggle ith bit | n ^ (1 << i) | Flip the i-th flag |
| Remove rightmost 1 | n & (n - 1) | Count bits, check power of 2 |
| Extract rightmost 1 | n & -n | Fenwick Trees, isolating bits |
# Counts the number of 1s in binary representation in O(1s) time def count_set_bits(n): count = 0 while n: n &= (n - 1) # drops the lowest set bit count += 1 return count
# All elements appear twice except one. Find it in O(N) time, O(1) space. def singleNumber(nums): res = 0 for num in nums: res ^= num return res
# True if n is a power of 2 (has exactly one 1-bit) def isPowerOfTwo(n): return n > 0 and (n & (n - 1)) == 0