Bit Manipulation

O(1) or O(log n)

Use bitwise operations to solve problems efficiently by treating integers as arrays of bits.

Time: O(1) or O(log n)Space: O(1)

When to Use

  • Finding single/missing numbers without extra space
  • Checking if number is power of two
  • Counting set bits or toggling specific bits
  • XOR tricks for finding unpaired elements

Pattern Variants

XOR Tricks

Use XOR properties: a ^ a = 0, a ^ 0 = a to find unique elements.

Use for: Single Number, missing number from sequence

Bit Masks

Use AND, OR masks to check, set, or clear specific bit positions.

Use for: Power of two checks, counting bits, subset generation

Shift Operations

Use left/right shifts to multiply/divide by powers of 2 or extract bits.

Use for: Reverse bits, counting leading zeros, bit extraction

Interactive Visualization

Code
1function singleNumber(nums) {
2 let result = 0
3
4 for (const num of nums) {
5 result = result ^ num
6 }
7
8 return result
9}
8-bit
76543210
Output
Input: [2, 1, 2]
Find: unique number
Step 1/12Find the number that appears only once. XOR trick: a ^ a = 0 and a ^ 0 = a.
1 / 12
Key Insight:XOR cancels paired numbers: a ^ a = 0. After XORing all elements, only the single number remains because its pair is missing.

Practice this Pattern

Go to Single Number

Single Number

Find the element that appears only once when all others appear twice using XOR

Go to Number of 1 Bits

Number of 1 Bits

Count the number of set bits (1s) in a binary number (Hamming Weight)

Go to Counting Bits

Counting Bits

Return array where ans[i] is the number of 1s in binary of i

Go to Reverse Bits

Reverse Bits

Reverse bits of a 32-bit unsigned integer

Go to Missing Number

Missing Number

Find the missing number in array [0, n] using XOR

Go to Power of Two

Power of Two

Check if a number is a power of two

Go to Sum of Two Integers

Sum of Two Integers

Add two integers without using + or - operators

Go to Single Number II

Single Number II

Find element appearing once when others appear 3 times

Go to Single Number III

Single Number III

Find two elements appearing once when others appear twice

Go to Bitwise AND of Range

Bitwise AND of Range

Find bitwise AND of all numbers in range [left, right]

Go to Number Complement

Number Complement

Flip all bits in binary representation

Go to Power of Four

Power of Four

Check if a number is a power of four

Go to Alternating Bits

Alternating Bits

Check if binary has alternating bits (101010...)

Go to Hamming Distance

Hamming Distance

Count differing bit positions between two numbers

Go to Maximum XOR

Maximum XOR

Find maximum XOR of any two numbers in array

Go to Maximum XOR of Two Numbers (Trie)

Maximum XOR of Two Numbers (Trie)

Use bitwise trie to maximize xor value