Bit manipulation coding interview questions

10 coding interview questions on bit manipulation and bitmasks, each with the correct answer and a full explanation.

Single Number: others appear twice, return the lone value.

def single_number(nums):
    result = [1]
    for x in nums:
        result [2] x
    return result
Show answer

Answer

def single_number(nums):
    result = 0
    for x in nums:
        result ^= x
    return result
  • Gap 1 is 0. Not 1: XOR starts from 0, its identity, and a start of 1 flips the lowest bit of the answer. Not nums[0]: The loop also visits nums[0], so it is XORed in twice and cancels out.
  • Gap 2 is ^=. Not +=: A sum keeps the pairs, so they never cancel to leave the single value. Not |=: OR never clears a bit, so pairs cannot cancel each other.

Count the 1 bits of n, one bit at a time.

def hamming_weight(n):
    count = 0
    while n:
        count += [1]
        n [2]
    return count
Show answer

Answer

def hamming_weight(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count
  • Gap 1 is n & 1. Not n % 10: That is the last decimal digit, not the last bit. Not n: This adds the whole number, not its lowest bit.
  • Gap 2 is >>= 1. Not //= 10: Dividing by 10 drops a decimal digit, but bits go in base 2. Not <<= 1: Shifting left grows n, so the loop never ends.
Number of 1 Bits uses this step. What prints?
n = 12  # 0b1100
print(n & (n - 1))
Show answer

Answer

8
n & (n - 1) clears the lowest set bit, so a loop of it runs once per 1 bit.
Reverse Bits builds the answer like this. What prints?
n, out = 0b1101, 0
for _ in range(4):
    out = (out << 1) | (n & 1)
    n >>= 1
print(bin(out))
Show answer

Answer

0b1011
Take n's lowest bit with n & 1 and push it into out with a left shift, so the bits come out reversed.
Counting Bits reuses smaller answers. What prints?
dp = [0] * 6
for i in range(1, 6):
    dp[i] = dp[i >> 1] + (i & 1)
print(dp)
Show answer

Answer

[0, 1, 1, 2, 1, 2]
i >> 1 drops the last bit, which i & 1 adds back, so each answer reuses a smaller one.

Compute x to the power n by squaring.

def my_pow(x, n):
    if n < 0:
        x, n = 1 / x, -n
    result = 1
    while n:
        if [1]:
            result *= x
        x = [2]
        n [3] 1
    return result
Show answer

Answer

def my_pow(x, n):
    if n < 0:
        x, n = 1 / x, -n
    result = 1
    while n:
        if n & 1:
            result *= x
        x = x * x
        n >>= 1
    return result
  • Gap 1 is n & 1. Not n % 2 == 0: x should join the result when the bit is 1, which means n is odd. Not n > 1: Bits are read one at a time, and the last 1 bit is skipped when n is 1.
  • Gap 2 is x * x. Not x * 2: That doubles x, but each step must square it, so x goes x, x**2, x**4. Not x ** x: x ** x raises x to the power of itself, not to the power 2.
  • Gap 3 is >>=. Not -=: Subtracting 1 changes the low bit but does not move to the next bit of n. Not <<=: Shifting left grows n, so the loop never ends.
Sum of Two Integers adds without +. What prints?
a, b = 5, 3
print(a ^ b, (a & b) << 1)
Show answer

Answer

6 2
a ^ b adds without carry and (a & b) << 1 is the carry, so 6 + 2 equals 5 + 3.
Subsets by bitmask. What prints?
nums = [1, 2]
n = len(nums)
out = []
for mask in range(1 << n):
    picked = [nums[i] for i in range(n) if mask >> i & 1]
    out.append(picked)
print(out)
Show answer

Answer

[[], [1], [2], [1, 2]]
Each mask is a yes or no choice per element, and mask >> i & 1 reads the choice for nums[i].

Single Number III: find both values that appear once.

def single_number_iii(nums):
    diff = 0
    for x in nums:
        diff ^= x
    low = [1]
    a = b = 0
    for x in nums:
        if [2]:
            a ^= x
        else:
            b ^= x
    return [a, b]
Show answer

Answer

def single_number_iii(nums):
    diff = 0
    for x in nums:
        diff ^= x
    low = diff & -diff
    a = b = 0
    for x in nums:
        if x & low:
            a ^= x
        else:
            b ^= x
    return [a, b]
  • Gap 1 is diff & -diff. Not diff & (diff - 1): That clears the lowest set bit, so the mask left can be 0 or hold several bits. Not diff & 1: That tests only the last bit, and the two values can agree on it.
  • Gap 2 is x & low. Not x & diff: Any x that shares a bit with diff passes, so the two values can land in one group. Not x == low: low is a single bit, so only a value equal to it joins the first group.
Shortest walk touching every node: the BFS state?
Show answer

Answer

(node, mask of visited nodes)
The mask says which nodes are seen, so BFS can revisit a node but never repeats a (node, mask) pair.

These questions come from the Coding Interview Patterns course in Bertopia.

More coding topics

Practise these on your commute