Skip to content
AdvancedAdvanced

Bit Manipulation

Use bitwise operations (AND, OR, XOR, shift) for efficient computation on integers.

Problem: Single Number

Find the number that appears once in [4, 1, 2, 1, 2]. Use XOR: a ^ a = 0, a ^ 0 = a

Array: [4, 1, 2, 1, 2]
Step 1/8
Speed:

When to Use

  • Find single/unique number
  • Power of two checks
  • Subset generation using bitmasks
  • Efficient integer operations

Key Indicators

  • XOR to find unique element
  • Power of two
  • Bitmask for subsets
  • Binary representation

Complexity

Time

O(n) or O(1)

Space

O(1)

Common Problems

Single NumberNumber of 1 BitsCounting BitsMissing NumberPower of Two

Code

# Find single number (all others appear twice)
result = 0
for num in arr:
    result ^= num  # XOR cancels pairs
return result

Want all 29 patterns with detailed visual walkthroughs?

The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.

Book Coming Soon ($4.99)