When interviewers ask you to work with integers, they often want you to reach for bit manipulation. The pattern is simple: treat each integer as a row of bits and use logical operators (AND, OR, XOR, NOT, shifts) to extract, combine, or flip those bits. Because a machine processes a word in a single instruction, these tricks usually run in O(1) time and O(1) extra space.
Spotting the Bit‑Manipulation Signal
| Cue in the statement | Typical intention |
|---|---|
| "without using extra data structures" | O(1) space, often a bit mask or XOR trick |
| "find the odd one out" or "single number" | Use XOR to cancel pairs |
| "count set bits" or "parity" | Use Brian Kernighan’s loop or built‑in popcount |
| "subset / power set" | Treat each subset as a bitmask of length n |
| "flip/turn on/off a bit" | Shift a 1 into the right position and apply OR/AND/NOT |
| "next greater number with same number of 1s" | Use a combination of right‑most set bit and carry propagation |
If you see any of these phrases, pause and ask yourself: Can I express the answer as a series of bitwise operations? That mental check often leads to the most concise solution.
A Worked Example: "Single Number"
Problem – Given an array where every integer appears exactly twice except one that appears once, return the unique integer.
Why bits? – Adding or subtracting numbers would need extra memory to count occurrences. XOR, however, has the property that a ^ a = 0 and a ^ 0 = a. Pairing each duplicate cancels it out, leaving only the lone value.
def single_number(nums):
"""Return the element that appears once.
Time: O(n) Space: O(1)
"""
result = 0
for n in nums:
result ^= n # flip bits where n has 1s
return result
Complexity – The loop runs once per element, so linear time. No auxiliary containers, so constant extra space.
Pitfalls
- Signed vs unsigned – In Python integers are unbounded, but in languages like Java or C++ you must be careful with sign extension when shifting.
- Assuming the array is non‑empty – Guard against an empty list; otherwise the XOR of zero elements is undefined for the interview question.
- Mixing types – XOR only works on integer types. Converting a string or float first will raise an error.
Core Bit‑Manipulation Techniques
- Masking –
num & maskisolates bits where mask has 1s. - Shifting –
num << kmoves bits left k places (multiply by 2^k).num >> kmoves right (divide, discarding low bits). - XOR toggling –
num ^ (1 << i)flips the i‑th bit. - Brian Kernighan’s loop – Repeatedly clear the lowest set bit:
while n: n &= n-1– runs in proportion to the number of 1s. - Right‑most set bit –
num & -numisolates the lowest 1; useful for next‑permutation problems.
Five Representative Practice Problems
1. Count Set Bits (Popcount)
Prompt – Return the number of 1s in the binary representation of a non‑negative integer.
Hint – Use n &= n-1 inside a loop; each iteration removes one 1. This runs in O(number of 1s) rather than O(bits).
2. Power of Two Check
Prompt – Determine if an integer is a power of two.
Hint – A power of two has exactly one set bit. Test n > 0 and (n & (n-1)) == 0.
3. Missing Number in a Sequence
Prompt – An array contains all numbers from 0 to n except one. Find the missing value.
Hint – XOR every index and every element together; duplicates cancel, leaving the missing number.
4. Reverse Bits of a 32‑bit Integer
Prompt – Reverse the order of bits and return the resulting integer. Hint – Iterate 32 times, shift a result left, and OR in the lowest bit of the input. Use a mask to keep within 32 bits.
5. Subset Sum with Bitmask
Prompt – Given a list of up to 20 integers, determine if any subset sums to a target value.
Hint – Enumerate all 2^n subsets using a bitmask loop: for mask in range(1 << n): and compute the sum by checking each bit.
These problems each spotlight a different primitive: masking, shifting, XOR cancellation, or enumeration via bitmask. Working through them builds a toolbox that interviewers expect you to pull from instinctively.
Common Mistakes and How to Avoid Them
- Off‑by‑one in shifts – Remember that the least‑significant bit is position 0. Shifting by
imeans1 << itargets the i‑th bit. - Neglecting edge cases – Zero, negative numbers, and maximum‑size integers often expose sign‑extension bugs.
- Over‑engineering – Sometimes a simple arithmetic solution is clearer. Use bits when they give a clear advantage in time or space.
- Hard‑coding word size – In Python you can ignore word size, but in C/C++ you must respect 32‑ or 64‑bit limits, especially when right‑shifting signed values.
When Not to Use Bit Tricks
If the problem statement emphasizes readability, or if the language already provides a built‑in function (bin(x).count('1'), Integer.bitCount()), a straightforward approach may be preferred. Also, if the interview is for a high‑level role where algorithmic depth is less critical, spend time on design rather than micro‑optimisation.
How to Practice This
- Write the core primitives – Implement masking, shifting, and the Kernighan loop in a notebook. Run them on random numbers to see how they behave.
- Solve one problem per day – Pick from the list above, code it without looking at solutions, then compare with the official answer.
- Explain aloud – Use Call Assistant to rehearse your explanation as if you were in an interview. Let it capture your flow and suggest follow‑up phrasing, keeping the focus on the bit‑level insight.
FAQ
Q: How many bits can I safely assume an integer has? A: In most interview languages,
intis 32 bits andlongis 64 bits, but clarify with the interviewer if the problem depends on word size.Q: Why is XOR useful for finding a unique element? A: XOR is associative and commutative, and a number XORed with itself yields zero. Pairing duplicates cancels them, leaving the lone value.
Q: Can I use Python's
binorpopcountbuilt‑ins? A: Yes, they are acceptable if the question doesn't explicitly require a manual implementation. Mention the built‑in and then show the manual version to demonstrate understanding.Q: What if the interview asks for a solution that works for negative numbers? A: Treat the number as its two's‑complement representation. Operations like
n & (n-1)still clear the lowest set bit, but be careful with right shifts—use unsigned shift operators where available.
Frequently asked questions
How many bits can I safely assume an integer has?
In most interview languages, `int` is 32 bits and `long` is 64 bits, but clarify with the interviewer if the problem depends on word size.
Why is XOR useful for finding a unique element?
XOR is associative and commutative, and a number XORed with itself yields zero. Pairing duplicates cancels them, leaving the lone value.
Can I use Python's `bin` or `popcount` built‑ins?
Yes, they are acceptable if the question doesn't explicitly require a manual implementation. Mention the built‑in and then show the manual version to demonstrate understanding.
What if the interview asks for a solution that works for negative numbers?
Treat the number as its two's‑complement representation. Operations like `n & (n-1)` still clear the lowest set bit, but be careful with right shifts—use unsigned shift operators where available.
#coding pattern#bit manipulation#interview prep#python#algorithm