Bit manipulation tricks for coding interviews
Bit manipulation in coding interviews comes down to about eight operations: test, set, clear and flip one bit with a shifted 1, isolate the lowest set bit with x & -x, drop it with x & (x - 1), cancel pairs with XOR, and treat an integer as a set of flags called a bitmask. Learn those, plus how your language handles negative numbers, and most bit questions turn into a few lines of code.
By Evin JohnPublished 9 min read
When to reach for bits
Bit tricks are rarely the only way to solve a problem, but they are often the way the interviewer is hoping for, usually because they bring extra memory down to O(1). These clues in a prompt are worth pausing on:
- Every value appears twice except one (or some other count): XOR or per-bit counting.
- Is this a power of two, or how many 1 bits does it have? The lowest-bit operations.
- Try every subset of up to roughly 20 items. Each integer from 0 to 2ⁿ - 1 is a subset.
- Add or subtract without the arithmetic operators. XOR for the sum without carries, AND plus a shift for the carries.
- Track a small set of on/off states compactly, such as which letters a word uses or which cells a row has filled.
- Reverse or rotate the bits of a fixed-width number. Shift bits out of one end and into the other.
The core operations on one number
Take x = 44, which is 101100 in binary. Bit positions count from 0 at the right, so bits 2, 3 and 5 are set. Every operation below builds a mask with a single 1 at position i by shifting: 1 << i.
| Goal | Expression | Result for x = 44 (101100) |
|---|---|---|
| Is bit 3 set? | (x >> 3) & 1 | 1, yes |
| Set bit 0 | x | (1 << 0) | 45 (101101) |
| Clear bit 2 | x & ~(1 << 2) | 40 (101000) |
| Flip bit 5 | x ^ (1 << 5) | 12 (001100) |
| Keep only the lowest 1 bit | x & -x | 4 (000100) |
| Remove the lowest 1 bit | x & (x - 1) | 40 (101000) |
| Count the 1 bits | Repeat x &= x - 1 until 0 | 3 |
| Power of two? | x > 0 and x & (x - 1) == 0 | No (64 would say yes) |
Why does x & (x - 1) drop the lowest 1 bit? Subtracting 1 turns the lowest 1 into a 0 and every 0 below it into a 1, leaving the higher bits alone. AND-ing with the original keeps the higher bits and wipes the rest. And x & -x works because in two's complement -x equals ~x + 1, which flips every bit above the lowest 1 while keeping that 1 and the zeros below it.
def bit_is_set(x, i):
return (x >> i) & 1 == 1
def with_bit(x, i):
return x | (1 << i)
def without_bit(x, i):
return x & ~(1 << i)
def flip_bit(x, i):
return x ^ (1 << i)
def lowest_bit(x):
return x & -x # isolates the lowest 1 bit (0 if x is 0)
def drop_lowest_bit(x):
return x & (x - 1)
def is_power_of_two(x):
return x > 0 and x & (x - 1) == 0
def count_ones(x):
# Kernighan's loop: one step per 1 bit. Use on non-negative x
# (mask negatives first, for example x & 0xFFFFFFFF).
count = 0
while x:
x &= x - 1
count += 1
return count// JavaScript bitwise operators work on 32-bit signed integers.
const bitIsSet = (x, i) => ((x >> i) & 1) === 1;
const withBit = (x, i) => x | (1 << i);
const withoutBit = (x, i) => x & ~(1 << i);
const flipBit = (x, i) => x ^ (1 << i);
const lowestBit = (x) => x & -x;
const dropLowestBit = (x) => x & (x - 1);
// Parentheses matter: === binds tighter than & in JavaScript.
const isPowerOfTwo = (x) => x > 0 && (x & (x - 1)) === 0;
function countOnes(x) {
let count = 0;
while (x !== 0) {
x &= x - 1; // also fine for negative 32-bit values
count++;
}
return count;
}
// Unsigned midpoint for binary search on non-negative indexes.
const midpoint = (lo, hi) => (lo + hi) >>> 1;The counting loop runs once per 1 bit, not once per bit position, which is why it is often called Kernighan's method. It is a nice detail to mention when an interviewer asks how many iterations it takes.
XOR: pairs cancel
XOR has three properties that make it the star of bit questions: a ^ a is 0, a ^ 0 is a, and order does not matter. So if every value in a list appears exactly twice except one, XOR-ing everything leaves the odd one out. For [7, 3, 9, 3, 7], the 7s cancel, the 3s cancel and 9 remains. It uses O(1) memory where a hash set would use O(n), and it works for negative numbers too.
def lone_value(nums):
# every value appears twice except one; pairs cancel under XOR
acc = 0
for v in nums:
acc ^= v
return accTwo close relatives use the same idea. To find the one missing number from 0 to n, XOR all the indexes and all the values together; every number present cancels with its index. When values appear three times except one, XOR is no longer enough, so count how many values have each bit set and take that count modulo 3.
Bitmasks as sets
An integer with n bits can stand for a subset of n items: bit i is 1 when item i is in. Counting from 0 to 2ⁿ - 1 therefore visits every subset exactly once. With items x, y and z, mask 5 (binary 101) means x and z. This is a clean way to enumerate subsets when n is small, and it is the state used in many dynamic programming problems over subsets, such as the traveling salesman table.
def all_subsets(items):
n = len(items)
out = []
for mask in range(1 << n): # each mask picks a subset
out.append([items[i] for i in range(n) if mask >> i & 1])
return outFor x, y, z this produces [], [x], [y], [x, y], [z], [x, z], [y, z], [x, y, z]. A useful extra: to walk every subset of a given mask, repeat sub = (sub - 1) & mask until it reaches 0.
Counting 1 bits for every number up to n
Shifting k right by one drops its last bit, and the dropped bit is k & 1. So the count for k equals the count for k >> 1, which is smaller and already known, plus that last bit. One pass fills a table for every number from 0 to n in O(n), instead of counting each number separately.
def ones_up_to(n):
# ones[k] = ones[k >> 1] + lowest bit of k, for every k from 0 to n
ones = [0] * (n + 1)
for k in range(1, n + 1):
ones[k] = ones[k >> 1] + (k & 1)
return onesNegative numbers and language differences
| Language | What to remember |
|---|---|
| Python | Integers have no fixed width, and a negative number behaves as if it had infinitely many leading 1 bits. Counting bits of -5 would loop forever, so mask first: -5 & 0xFFFFFFFF is 4294967291, which has 31 ones. Right shift floors, so -5 >> 1 is -3. |
| JavaScript | Bitwise operators convert numbers to 32-bit signed integers and back. 1 << 31 is negative. Use >>> 0 to read a result as unsigned, and do not use bitwise tricks on values that may exceed 32 bits. |
| C and C++ | Prefer unsigned types for shifts and masks. Shifting by the type's width or more is undefined behavior, and shifting a 1 into the sign bit of a signed int was undefined before C++20. Compilers offer popcount helpers such as __builtin_popcount in GCC and Clang, and std::popcount in C++20. |
One precedence trap catches people in JavaScript, C and C++: the equality operators bind tighter than &, so x & (x - 1) == 0 is read as x & ((x - 1) == 0). Wrap the AND in parentheses. Python happens to evaluate it the way you meant, which hides the bug until you switch languages.
The unsigned shift also gives a quick binary-search midpoint in JavaScript: (lo + hi) >>> 1 halves and floors in one step, and it is correct whenever lo + hi stays below 2³², which holds for any array shorter than 2³¹ elements. Find Peak Element uses it.
Practice problems and the trick each one uses
| Problem | Trick | Cost |
|---|---|---|
| Single Number | XOR every value so pairs cancel | O(n) time, O(1) space |
| Number of 1 Bits | Kernighan's loop, or a popcount helper | O(number of 1 bits) |
| Counting Bits | Table from k >> 1 plus the last bit | O(n) |
| Missing Number | XOR indexes with values | O(n) time, O(1) space |
| Reverse Bits | Shift each bit out of one end and into the other, 32 times | O(1) for fixed width |
| Sum of Two Integers | XOR for the sum, AND then shift for the carry, repeat | O(width) |
| Subsets | Count masks from 0 to 2ⁿ - 1 | O(2ⁿ · n) |
| Find Peak Element | Not a bit problem, but uses the unsigned midpoint | O(log n) |
Common mistakes
- Forgetting parentheses around & in languages where == binds tighter.
- Running a counting loop on a negative Python integer without masking it to a fixed width first.
- Using JavaScript bitwise operators on numbers beyond 32 bits, which silently truncates them.
- Treating 0 as a power of two. The x > 0 check is part of the trick.
- Using XOR swap in production code. It is a fun fact, but it zeroes the value when both names refer to the same memory, and it is usually no faster than a temporary variable.
- Reaching for bits when a plain counter or set would be clearer. If the space saving does not matter, say so and choose readability.
Saying it clearly
Fictional example
- Candidate
- A hash set would work in linear time but uses linear memory. There's an O(1) memory option with XOR.
- Candidate
- A value XOR itself is zero, zero XOR a value is the value, and XOR doesn't care about order. So when I XOR the whole list, every pair cancels and the single value is what's left.
- Candidate
- It also works with negative numbers, since XOR acts on the bits directly. If values appeared three times instead of twice, I'd count each bit position modulo three instead.
Related walkthroughs
Find Peak Element is a binary search where the unsigned-shift midpoint appears. Generate Parentheses enumerates arrangements by backtracking, a good contrast with enumerating subsets by counting masks. The coding problems hub groups every walkthrough by pattern.
Drilling bit tricks with Natively
When you practice on Mac or Windows, Natively can read a bit-manipulation prompt from a screenshot, and you can ask it why x & (x - 1) removes the lowest set bit or how negative values behave in your language. Mock sessions are transcribed and saved with notes, so you can check whether you explained the XOR properties before writing the loop. The AI interview assistant page has the details.
Questions people ask
What bit manipulation tricks should I know for coding interviews?
Testing, setting, clearing and flipping a bit with 1 << i; x & (x - 1) to drop the lowest 1 bit; x & -x to keep it; XOR to cancel pairs; and integers as bitmasks for subsets. Also know how your language treats negative numbers.
What does x & (x - 1) do?
It clears the lowest set bit of x. Subtracting 1 flips that bit and every bit below it, so the AND keeps only the higher bits. Repeating it until x is 0 counts the 1 bits, and x > 0 with x & (x - 1) equal to 0 means x is a power of two.
How does XOR find the single number?
A value XOR itself is 0, a value XOR 0 is the value, and XOR order does not matter. XOR-ing a list where every value appears twice except one cancels the pairs and leaves the single value, using O(1) memory.
Why do bit tricks behave differently in Python and JavaScript?
Python integers have no fixed width, so negative numbers act as if they had endless leading 1 bits; mask with 0xFFFFFFFF for 32-bit behavior. JavaScript bitwise operators convert values to 32-bit signed integers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
