DSA · Patterns, not puzzles
What bit manipulation tricks are useful in interviews?
Short answer
Useful tricks include XOR for finding a lone value, value & (value - 1) to clear the lowest set bit, and shifts to test or set individual bits. They often reduce space to O(1).
Bit operations work directly on the binary representation. They are fast, but they are also easy to get wrong with signs and fixed-width integers. In JavaScript, bitwise operators coerce operands to 32-bit signed integers, which matters for large values.
function singleNumber(values) {
let result = 0;
for (const value of values) result ^= value;
return result;
}
function countSetBits(value) {
let count = 0;
while (value > 0) {
value &= value - 1;
count += 1;
}
return count;
}
function isSet(value, position) {
return (value & (1 << position)) !== 0;
}The core identities
- x ^ x = 0 and x ^ 0 = x, so XOR finds the value that appears once
- x & (x - 1) clears the lowest set bit
- x & -x isolates the lowest set bit
- x ^ (1 << k) toggles bit k
- x >> 1 divides by two for non-negative integers, while >>> shifts unsigned
Subsets can be enumerated with a bitmask from 0 to (1 << n) - 1. That is useful for small n, but the exponential bound is real. Do not use a bitmask when n is large enough that 2^n is impractical.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does XOR find the element that appears once?
- 2What does x & (x - 1) do?
- 3How do you enumerate all subsets with a bitmask?
- 4What are the limitations of bitwise operators in JavaScript?
Say it in the interview
XOR is useful because a value XOR itself is zero, so pairs cancel and the remaining value is the one that appeared once. Clearing the lowest set bit with x & (x - 1) lets me count set bits efficiently. I also use masks to test, set or toggle individual positions. In JavaScript I remember that bitwise operations are 32-bit, so I switch to BigInt for wider values.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.