Notes
All notes

Bit Manipulation (LeetCode #17)

Computers store numbers as bits — a row of 0s and 1s. Bit manipulation works on those bits directly, turning loops into single operations and data structures into \(O(1)\) space. This post covers the seven NeetCode Bit Manipulation problems.

The technique

With a = 0b1100 (12), b = 0b1010 (10):

Op a op b Meaning
& 0b1000 1 only if both are 1
\| 0b1110 1 if either is 1
^ 0b0110 1 if the bits differ
~ flips NOT
<< ×2 shift left
>> ÷2 shift right

Key identities:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.5cm, font=\small\bfseries}]
  \foreach \v [count=\i from 0] in {1,0,1,1,0,1,0,0} { \node[c, fill=blue!8] at (\i*0.6,0) {\v}; }
  \foreach \v [count=\i from 0] in {1,0,1,1,0,1,0,0} { \node[c, fill=blue!8] at (\i*0.6,-0.6) {\v}; }
  \node[font=\small, anchor=east] at (-0.4,0) {a};
  \node[font=\small, anchor=east] at (-0.4,-0.6) {a};
  \node[font=\large] at (-0.4,-1.2) {$\oplus$};
  \foreach \i in {0,...,7} { \node[c, fill=green!25] at (\i*0.6,-1.2) {0}; }
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.1,-1.6) {a XOR a = 0 for every bit};
\end{tikzpicture}

Single Number

The question. Every value appears twice except one; find it.

Input:  [4,1,2,1,2]  -> 4

The idea. XOR the array; pairs cancel, the singleton survives.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \foreach \v [count=\i from 0] in {4,1,2,1,2} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
  \draw[<->, thick, orange!80!black] (0.66,-0.35) to[bend right=25] (1.98,-0.35);
  \draw[<->, thick, orange!80!black] (1.32,-0.35) to[bend right=25] (2.64,-0.35);
  \node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.65,-0.85) {pairs cancel};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.65,-1.25) {x ^ x = 0, so 0 ^ 4 = 4};
\end{tikzpicture}
def single_number(nums):
    result = 0
    for x in nums:
        result ^= x
    return result

\(O(n)\) time, \(O(1)\) space.

Number of 1 Bits

The question. Count the set bits (Hamming weight).

The idea — Brian Kernighan. n & (n - 1) clears the lowest set bit, so the loop runs once per set bit.

def hamming_weight(n):
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count

\(O(\text{number of set bits})\).

Counting Bits

The question. For every i in 0..n, count its set bits — in \(O(n)\).

The idea. bits[i] = bits[i >> 1] + (i & 1): drop the last bit and add it back.

def count_bits(n):
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = dp[i >> 1] + (i & 1)
    return dp

\(O(n)\) time and space.

Reverse Bits

The question. Reverse the 32 bits of an integer.

def reverse_bits(n):
    result = 0
    for _ in range(32):
        result = (result << 1) | (n & 1)   # append the low bit
        n >>= 1
    return result

\(O(32) = O(1)\).

Missing Number

The question. An array contains n distinct numbers from 0..n; find the one missing.

Input:  [3,0,1]  -> 2

The idea. Two ways. XOR every index 0..n with every value: each present number cancels its index, leaving the missing one. Or use the sum formula n(n+1)/2 and subtract the actual sum (watch for overflow in fixed-width languages).

Walk it through on [3,0,1]: XOR of 0^1^2^3 (indices) with 3^0^1 (values) = 2.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \foreach \v [count=\i from 0] in {0,1,2,3} { \node[c, fill=blue!8] at (\i*0.66,0.9) {\v}; }
  \foreach \v [count=\i from 0] in {3,0,1} { \node[c, fill=orange!12] at (\i*0.66+0.2,0) {\v}; }
  \node[font=\scriptsize\ttfamily, anchor=east] at (-0.4,0.9) {index};
  \node[font=\scriptsize\ttfamily, anchor=east] at (-0.4,0) {value};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.0,-0.55) {everything pairs off except the missing 2};
\end{tikzpicture}
def missing_number(nums):
    result = len(nums)
    for i, x in enumerate(nums):
        result ^= i ^ x          # index XOR value
    return result

\(O(n)\) time, \(O(1)\) space. The XOR version cannot overflow.

Sum of Two Integers

The question. Add two integers without + or -.

The idea. XOR gives the sum without carries; AND shifted left gives the carries. Repeat until no carries remain.

def get_sum(a, b):
    mask = 0xFFFFFFFF
    while b & mask:
        carry = (a & b) << 1
        a ^= b                 # sum without carries
        b = carry              # carries to add next
    return a & mask if b > 0 else a

\(O(1)\) iterations.

Reverse Integer

The question. Reverse the digits of a 32-bit signed integer; return 0 if the result overflows.

Input:  123  -> 321
Input:  -123 -> -321
Input:  1534236469 -> 0     (reversed overflows int32)

The idea. Repeatedly take the last digit (x % 10) and append it (result = result * 10 + digit), watching for overflow past \(2^{31}-1\) or below \(-2^{31}\).

Walk it through on 123: digit 3 → result 3; digit 2 → 32; digit 1 → 321.

def reverse_integer(x):
    sign = -1 if x < 0 else 1
    x = abs(x)
    result = 0
    limit = 2**31 - 1
    while x:
        result = result * 10 + x % 10
        x //= 10
        if result > limit:                 # would overflow int32
            return 0
    return sign * result

\(O(\log_{10} n)\) time, \(O(1)\) space.

Pitfalls

QQuestionSelf-check

Why does XOR find the single number / the missing number? How does n & (n - 1) speed up bit counting?

ASolution

XOR is commutative and associative with a ^ a = 0, so duplicates cancel — for the missing number, XORing each index with its value leaves the unmatched index. n & (n - 1) clears the lowest set bit, so the loop runs once per set bit rather than once per bit position.

Next: Math and Geometry (LeetCode #18) — matrices, number theory, and fast exponentiation.