Bits and string matching · mid
Bit tricks that are actually asked
A few bit tricks (x & (x - 1) clears the lowest set bit, XOR cancels pairs, masks store sets of flags) solve the bit questions that coding rounds ask, and the integer width of each language decides the edge cases.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Width: Java int has 32 bits and long has 64; shifts count modulo the width (1 << 32 is 1 in Java), and 1 << 31 is negative; write 1L << 40 for a 64-bit mask. Python ints have no limit, so ~x is -x - 1 and you mask with & 0xFFFFFFFF to simulate 32 bits. In C++ use unsigned types for bit work; a shift by the width or more is undefined.
- x & 1 tests odd or even; x & (x - 1) clears the lowest set bit (count bits by repeating it); a power of two has exactly one bit: x > 0 and (x & (x - 1)) == 0.
- XOR: a ^ a = 0 and a ^ 0 = a, so XOR of all numbers leaves the one that appears once (when the others appear twice).
- Flags and permissions: READ = 1, WRITE = 2, ADMIN = 4; has = (mask & FLAG) != 0; add = mask | FLAG; remove = mask & ~FLAG.
- Subsets by mask: for mask from 0 to 2^n - 1, bit i set means item i is included.
- Shifts: in Java, >> keeps the sign and >>> fills with zeros; Python has only >> (it keeps the sign); in C++ shifting a negative signed value to the right depends on the compiler before C++20.
- Library helpers exist (Java Integer.bitCount, Python int.bit_count in 3.10 and later, C++ std::popcount in C++20), but the interviewer usually asks for the trick.
The red pen
Common traps: mistake → fix
Mistake: In C++ and Java, x & 1 == 0 tests even
Fix: == binds tighter than &, so it means x & (1 == 0); write (x & 1) == 0 (Python reads it the expected way).
Mistake: ~x is 'not x' as a boolean
Fix: it flips every bit, so it equals -x - 1.
Mistake: 1 << 40 is a 64-bit mask in Java
Fix: it is an int shift, so the count is taken modulo 32 and the result is 256; write 1L << 40.
Easy to hard
Questions interviewers ask, easy to hard
- Find the single number when every other appears twice.
- Count the set bits of a number.
- Check whether n is a power of two.
- Store and check user permissions as bit flags.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.