Skip to main content

Pattern · 12 problems

Bit Manipulation Interview Problems

Bit problems look like magic until you learn four moves. After that they are small and mechanical.

Start with Counting Bits

Free: write the code and run it, no sign-up. Read the problem here; code it on a laptop.

When I reach for it

  • The statement bans extra space or restricts operators.
  • Numbers act as flags, masks or XOR pairs.
  • One odd value hides among pairs.

Problems, easiest first

6 easy · 6 medium · 0 hard. Open one to read it, then write it in the free editor.

The idea

XOR cancels equal values: x ^ x is 0 and x ^ 0 is x. XOR a whole list, and only the value without a partner survives.

Learn four moves. x & 1 reads the lowest bit, and x >> 1 drops it. x & (x - 1) clears the lowest set bit, and 1 << i builds a mask.

count = 0
while n:
    n &= n - 1     # clears the lowest set bit
    count += 1
return count
Count the set bits. Each pass clears the lowest one, so the loop runs once per set bit. Python shown; the idea carries to every language in the editor.

Where it goes wrong

  • Python ints never overflow. Other languages do, so ask about the width.
  • Operator precedence. Put parentheses around every bit operation.
  • Negative numbers and the two kinds of right shift.

Say this before you type. Say what each bit means in this problem before you shift or mask anything.

Where Coco comes in

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

Questions people ask

Why does XOR find the single number?
Equal values cancel to zero, and zero changes nothing. Every paired value disappears, so the unpaired one is left.
Do interviewers still ask bit questions?
Some do. The questions are short and test whether you stay precise, so they make a quick warm-up.

Meet these next

Fin and Coco are characters, not people. strongyes.io is independent. Leo builds it with AI agents.