NeetCode 150, stage 18: Bit Manipulation

← Math and Geometry · All 150 problems

An integer is a row of bits, and a few operators change those bits directly. This stage trains five small tricks with XOR, AND and the shifts, and one digit loop that stays in the 32-bit range. Each trick is a short loop, so you must know why it works and not only its code.

Problems on this page

#ProblemLevelPatternTemplate
1136. Single NumberEasyXOR cancels pairsA: XOR cancels pairs
2191. Number of 1 BitsEasyRemove the lowest set bitB: Remove the lowest set bit
3338. Counting BitsEasyDP on bitsC: DP on bits
4190. Reverse BitsEasyShift in and shift outD: Shift in and shift out
5268. Missing NumberEasyXOR of indexes and valuesA: XOR cancels pairs
6371. Sum of Two IntegersMediumAdd with XOR and carryE: Add with XOR and carry
77. Reverse IntegerMediumDigit loop with an overflow checkF: Digit loop with an overflow check

Templates to memorize

Template A: XOR cancels pairs

Signal

Each value appears two times, and one value appears only one time. Or one number of a full range is missing. The problem asks for O(1) extra space, so a hash map is not permitted.

// TEMPLATE A: XOR cancels pairs. x ^ x == 0, x ^ 0 == x, and the order does
// not matter.
func xorAll(nums []int) int {
    res := 0 // 1. START at 0, the value that changes nothing
    for _, x := range nums {
        res ^= x // 2. FOLD: the second copy of a value removes the first
    }
    return res // only the value with no partner is left
}
 
// To find the missing number of 0..n, the indexes are the partners:
// start at n, and fold each index with each value.
func missingFromRange(nums []int) int {
    res := len(nums)
    for i, x := range nums {
        res ^= i ^ x
    }
    return res
}

The moves are START at 0, then FOLD each value with XOR. Equal values cancel, and the order does not matter. For a missing number, the indexes are the partners of the values. Start at n, because the loop does not give the index n.

Say it

“XOR of a number with itself is zero, so every pair cancels and the single one is left. One pass, O(n) time and O(1) space.”

Template B: Remove the lowest set bit

Signal

The problem counts the 1 bits of a number, or asks if a number is a power of two.

// TEMPLATE B: n & (n-1) removes the lowest set bit. 1100 & 1011 == 1000.
func countSetBits(n int) int {
    count := 0
    for n != 0 {
        n &= n - 1 // 1. REMOVE the lowest set bit
        count++    // 2. COUNT the removal
    }
    return count
}
 
// A power of two has exactly one set bit, so one removal gives 0.
func isPowerOfTwo(n int) bool {
    return n > 0 && n&(n-1) == 0
}

The moves are REMOVE, then COUNT. The subtraction n - 1 changes the lowest 1 bit to 0 and the zeros after it to 1. The AND then clears all those positions. The loop runs one time for each set bit, not one time for each bit.

Say it

“n and n minus one clears the lowest set bit, so the loop runs once per set bit instead of 32 times.”

Template C: DP on bits

Signal

The problem asks for the bit count of each number from 0 to n, in O(n) time.

// TEMPLATE C: DP on bits. The answer for i comes from a smaller number.
func bitCounts(n int) []int {
    bits := make([]int, n+1) // 1. BASE: bits[0] == 0
    for i := 1; i <= n; i++ {
        // 2. REUSE the answer for i >> 1, which is i with no last bit.
        // 3. ADD the last bit, i & 1.
        bits[i] = bits[i>>1] + (i & 1)
    }
    return bits
}

The moves are BASE, REUSE, then ADD. The number i >> 1 is i with no last bit, and it is smaller than i. So its answer is already in the slice. Add i & 1, which is the last bit.

Say it

“The bit count of i is the bit count of i shifted right by one, plus its last bit. That’s one lookup per number, so O(n) in total.”

Template D: Shift in and shift out

Signal

The problem asks you to reverse the bits of a number, or to build a number from the bits of a second number.

// TEMPLATE D: shift in and shift out. Move the bits from n to res, one at a
// time.
func reverse32(n uint32) uint32 {
    var res uint32
    for i := 0; i < 32; i++ { // a fixed count: the leading zeros move too
        // 1. SHIFT IN: make room, then take the last bit of n
        res = res<<1 | n&1
        n >>= 1 // 2. SHIFT OUT: drop that bit from n
    }
    return res
}

The moves are SHIFT IN, then SHIFT OUT. Use a fixed count of 32 steps and not for n != 0. If the loop stops early, the leading zeros of n do not move to the result.

Say it

“I pop the lowest bit of n and push it onto the result, 32 times. The first bit out ends up as the highest bit.”

Template E: Add with XOR and carry

Signal

The problem asks for a sum, and the operators + and - are not permitted.

// TEMPLATE E: add with XOR and carry, on 32 bits.
func addBits(a, b uint32) uint32 {
    for b != 0 { // b is the carry that is not yet added
        // 1. CARRY: where the two bits are 1, moved left
        carry := (a & b) << 1
        a ^= b    // 2. SUM of the bits with no carry
        b = carry // 3. REPEAT until no carry is left
    }
    return a
}

The moves are CARRY, SUM, then REPEAT. XOR is addition with no carry. AND finds the carry, and the shift moves it one position to the left. In Go, do the loop on uint32 and convert the result with int(int32(x)).

Say it

“XOR adds without carrying, AND shifted left is the carry, and I repeat until the carry is zero. On 32 bits that’s at most 32 rounds.”

Template F: Digit loop with an overflow check

Signal

The problem builds a number digit by digit, and the result must stay in the 32-bit range. The problem says that 64-bit storage is not permitted.

// TEMPLATE F: digit loop with an overflow check. Build a number digit by
// digit
// and stay in the int32 range. Returns 0 when the result does not fit.
func reverseDigits(x int) int {
    res := 0
    for x != 0 {
        digit := x % 10 // 1. POP the last digit (it has the sign of x)
        x /= 10
        // 2. CHECK before the multiplication, with the limit divided by 10.
        if res > math.MaxInt32/10 || (res == math.MaxInt32/10 && digit > math.MaxInt32%10) {
            return 0
        }
        if res < math.MinInt32/10 || (res == math.MinInt32/10 && digit < math.MinInt32%10) {
            return 0
        }
        res = res*10 + digit // 3. PUSH the digit
    }
    return res
}

The moves are POP, CHECK, then PUSH. Do the check before the multiplication, and compare with the limit divided by 10. A check after the multiplication is too late in a 32-bit language, because the value already wrapped around.

Say it

“Before I multiply by ten I compare the result with MaxInt32 over ten, so the overflow never happens. It’s the usual pop and push digit loop.”

Mistakes in this stage

  • Go has no ~ operator. Write ^x for NOT, and a &^ b for “a AND NOT b”.
  • & and << have a higher precedence than + in Go, and in C they are lower. Add parentheses when you mix them.
  • >> on a negative int keeps the sign bit. So the loop for n != 0 { n >>= 1 } never stops for a negative n.
  • Go’s int has 64 bits on LeetCode. A 32-bit overflow does not occur by itself, so convert through uint32 and int32 when the problem needs it.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

136. Single Number

LeetCode 136 · Easy

191. Number of 1 Bits

LeetCode 191 · Easy

338. Counting Bits

LeetCode 338 · Easy

190. Reverse Bits

LeetCode 190 · Easy

268. Missing Number

LeetCode 268 · Easy

371. Sum of Two Integers

LeetCode 371 · Medium

7. Reverse Integer

LeetCode 7 · Medium


← Math and Geometry · All 150 problems