Pattern #34

Bit Manipulation

Important interview questions, thinking patterns, XOR cancellation, Kernighan's bit counting, Subsets bitmasking, Go operators, and interview rules.

Must Solve

16 core questions — solve these first.

  1. 1.Single Number
    easy
  2. 2.Number of 1 Bits
    easy
  3. 3.Counting Bits
    easy
  4. 4.Reverse Bits
    easy
  5. 5.Power of Two
    easy
  6. 6.Missing Number
    easy
  7. 7.Single Number II
    medium
  8. 8.Single Number III
    medium
  9. 9.Bitwise AND of Numbers Range
    medium
  10. 10.Sum of Two Integers
    medium
  11. 11.Minimum Bit Flips to Convert Number
    easy
  12. 12.Hamming Distance
    easy
  13. 13.Find the Difference
    easy
  14. 14.Maximum XOR of Two Numbers in an Array
    medium
  15. 15.Subsets Using Bitmask
    medium
  16. 16.Maximum Product of Word Lengths
    medium

Also Important

9 more questions worth practicing.

  1. 17.Power of Four
    easy
  2. 18.Binary Number with Alternating Bits
    easy
  3. 19.Complement of Base 10 Integer
    easy
  4. 20.Count Triplets That Can Form Two Arrays of Equal XOR
    medium
  5. 21.XOR Queries of a Subarray
    medium
  6. 22.Decode XORed Array
    easy
  7. 23.Gray Code
    medium
  8. 24.Bitwise ORs of Subarrays
    medium
  9. 25.Minimum Flips to Make a OR b == c
    medium

How to Think

  1. Need check one flag quickly?Bit Mask (n & (1 << i))
  2. Every number appears twice except one?XOR (x ^ x = 0, x ^ 0 = x)
  3. Need know if bit i is ON?AND (n & (1 << i) != 0)
  4. Need turn bit ON?OR (n | (1 << i))
  5. Need toggle a bit?XOR (n ^ (1 << i))
  6. Need turn bit OFF?AND NOT (n &^ (1 << i) in Go)
  7. Need all subsets and N is small?Bitmask (loop 0 to 2^N - 1)

Go Bit Manipulation Code Templates

Core Bitwise Operators in Go

// Check if bit i is set (ON)
func isBitSet(n int, i int) bool {
    return (n & (1 << i)) != 0
}

// Set bit i (turn ON)
func setBit(n int, i int) int {
    return n | (1 << i)
}

// Clear bit i (turn OFF using Go AND NOT &^ operator)
func clearBit(n int, i int) int {
    return n &^ (1 << i)
}

// Toggle bit i
func toggleBit(n int, i int) int {
    return n ^ (1 << i)
}

// Remove lowest set bit (Brian Kernighan)
func dropLowestSetBit(n int) int {
    return n & (n - 1)
}

👉 Go special clear operator: &^ (AND NOT)!

Core Operators & Essential Bit Tricks

1. Power of Two Check

A power of two has exactly one set bit in binary: n > 0 && (n & (n - 1)) == 0.

2. Count Set Bits (Kernighan)

Looping n = n & (n - 1) drops the lowest set bit in each step, completing in O(set_bits) time!

3. Isolate Lowest Set Bit

diff = n & -nisolates the rightmost 1-bit in two's-complement representation (used in Single Number III & Fenwick Tree).

4. Hamming Distance

Number of differing bits between x and y is simply the set bit count of x ^ y.

Subsets Bitmasking Generation (O(2^N))

When N <= 15, every subset corresponds to an integer mask from 0 to (1 << N) - 1:

func subsets(nums []int) [][]int {
    n := len(nums)
    total := 1 << n // 2^N subsets
    result := make([][]int, 0, total)

    for mask := 0; mask < total; mask++ {
        curr := []int{}
        for i := 0; i < n; i++ {
            if (mask & (1 << i)) != 0 {
                curr = append(curr, nums[i])
            }
        }
        result = append(result, curr)
    }
    return result
}
Visual Memory Rule
AND (&)        → Check if bit is set
OR (|)         → Set bit (turn ON)
XOR (^)        → Toggle bit / Cancel equal pairs (x^x=0)
AND NOT (&^)   → Clear bit (turn OFF in Go)
n & (n - 1)    → Drop lowest 1 bit
n & -n         → Isolate lowest 1 bit

💡 Golden Rule: "Think of an integer as a row of tiny ON/OFF switches, and use bit operators to control those switches directly."

Common Interview Mistakes

1. Confusing OR and XOR

Remembering 1 | 1 = 1 (OR sets both) vs 1 ^ 1 = 0 (XOR cancels duplicates!).

2. Wrong 1-Based Bit Position

Bit positions are 0-indexed! The rightmost LSB is bit 0 (1 << 0 = 1).

3. Forgetting Operator Parentheses

Writing n & 1 << i == 0 instead of (n & (1 << i)) == 0 due to lower operator precedence!

4. Using XOR Without Pair Guarantee

XOR cancellation x ^ x = 0 only works when duplicates appear an EVEN number of times! (For 3 times use bit counting).

Interview Rules

  1. 1. Duplicate pairs + one unique? → XOR (x ^ x = 0)
  2. 2. Check bit i?(n & (1 << i)) != 0
  3. 3. Set bit i?n | (1 << i)
  4. 4. Toggle bit i?n ^ (1 << i)
  5. 5. Clear bit i in Go?n &^ (1 << i)
  6. 6. Count set 1-bits? → Brian Kernighan (n & (n - 1))
  7. 7. Subsets for small N? → Bitmask loop from 0 to (1 << N) - 1
  8. 8. Maximum XOR of array pairs? → Bit Trie (choose opposite binary bit high to low)

Small Rules

  1. Rule 1: XOR of identical values cancels to 0 (x ^ x = 0, x ^ 0 = x).
  2. Rule 2: Always wrap bitwise expressions in explicit parentheses to avoid precedence errors.
  3. Rule 3:n & (n - 1) clears the rightmost set 1-bit.
  4. Rule 4:n & -n isolates the rightmost set 1-bit.
  5. Rule 5:Go uses the &^ (AND NOT) operator for bit clearing.

Production Thinking

RBAC / Unix Bitwise PermissionsStore READ=1, WRITE=2, DELETE=4, ADMIN=8 in single integer bitmap

Feature Flag Compact PackingPack 32/64 boolean feature flags into single uint64 bitmask

Network Protocol Flag HeadersRead TCP ACK, SYN, FIN flags via bitwise AND masks

Hardware / Embedded RegistersDirectly control hardware device status registers via bit manipulation

Remember This

AND         → Check
OR          → Set
XOR         → Toggle / cancel duplicates
AND NOT     → Clear (&^ in Go)
x ^ x       → 0
x ^ 0       → x
n & (n-1)   → Remove lowest set bit
Power of 2  → n > 0 && (n & (n-1)) == 0
Subsets     → Bitmask 0..2^N-1

💡 Golden Rule: "Think of an integer as a row of tiny ON/OFF switches, and use bit operators to control those switches directly."