Skip to the solution
MediumDSA10 min read

What are the most useful bit manipulation tricks for interviews?

134 views

The problem

Question presented to candidate: "Walk me through the bit manipulation tricks you would actually use in a coding interview. For each, tell me the expression, why it works, and anything about Python integers that changes how you write it."

What a strong answer should cover:

  • The single-bit operations with a mask: test (x >> i) & 1, set x | (1 << i), clear x & ~(1 << i), toggle x ^ (1 << i).
  • The lowest-set-bit pair: x & (x - 1) clears it, x & -x isolates it; the power-of-two test with the x > 0 guard.
  • XOR properties (a ^ a == 0, a ^ 0 == a) and their uses: single number, missing number, Hamming distance.
  • Bitmasks as sets: enumerate subsets with range(1 << n), submasks with sub = (sub - 1) & mask, and the 3^n total.
  • Python details: ints are unbounded (no overflow, no >>>), negatives act like infinite leading 1s so you mask with & 0xFFFFFFFF to emulate 32 bits, int.bit_count() (3.10+) and int.bit_length(), and & binds tighter than == in Python (unlike C-family languages).

Code / implementation expected: Optional โ€” short Python expressions for each trick, ideally with a small demo on one number.

  • dsa
  • bit-manipulation

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 15 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonSingle-bit and lowest-bit tricks on x = 44
PythonBitmasks as sets: subsets, set operations, submasks, 3^n
PythonEmulating 32-bit integers in Python

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 122 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the cheapest flight with at most K stops?

Continue