Skip to content

Software interviews

Bit manipulation for coding interviews: the operations that come up

Bit manipulation means working on the binary digits of a whole number directly. Interviews use a small set of operations, and a handful of tricks built from them: count the 1 bits, cancel pairs with exclusive-or, and treat a number as a set of positions. This page defines the operations, shows each on one example, works three patterns and gives four original problems with answers a separate program recomputes. It uses whole numbers that are zero or more throughout.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What bit manipulation is and why it is fast

A whole number can be written in binary, with each digit a 1 or a 0 in a position worth a power of two. The NIST Dictionary of Algorithms and Data Structures defines a bit vector as an array of bits, and points out that a computer word is itself an array of bits, which is why such vectors are cheap to work with. That is the reason the topic exists: one machine operation works on every position of a word at once, so a whole set of yes or no flags can be tested or combined in one step.

A useful way to read a number in binary is as a set of positions. Position 0 is the rightmost digit. The number 12 is 1100, so positions 2 and 3 are set. The Python tutorial’s section on sets describes a set as an unordered collection with no duplicate elements, and lists union, intersection, difference and symmetric difference as the operations on sets. Each of those has a bit operation that does the same thing on numbers read this way, which is the link between the two ideas and the reason a mask can stand for a subset.

The operations below are our own definitions, computed on one example. We take a = 12, which is 1100, and b = 10, which is 1010. The page works on whole numbers that are zero or more, so that the results are the same in any language.

The bit operations that come up, shown on a = 12 (1100) and b = 10 (1010)
OperationWrittenRuleResultSame as, on sets of positions
ANDa & b1 where both have 18 (1000)Intersection
ORa | b1 where either has 114 (1110)Union
Exclusive-ora ^ b1 where the bits differ6 (0110)Symmetric difference
Shift left by 1a << 1Move every bit up one place24 (11000)Double the number
Shift right by 1a >> 1Move every bit down one place, drop the last6 (110)Halve and round down
Test bit i(a >> i) & 1Read position iFor i = 2: 1Is i in the set
Set bit ia | (1 << i)Force position i to 1For i = 0: 13Add i to the set
Toggle bit ia ^ (1 << i)Flip position iFor i = 3: 4Add or remove i
Clear the lowest 1 bita & (a - 1)Subtracting 1 flips the lowest 1 and the zeros below it8 (1000)Remove the smallest element

The last row is the trick to learn first. Subtracting 1 from a number turns its lowest 1 bit into a 0 and every 0 below it into a 1, so a & (a - 1) keeps everything above the lowest 1 and clears the rest. Counting how many times you can do this before reaching 0 counts the 1 bits, in a loop that runs once per 1 bit. That is our own derivation, and it is easy to confirm on 12: it gives 8, then 0, so there are two 1 bits.

The problem signals that call for bit operations

Bit tricks are a sharp tool, and most problems do not need them. Look for the signals below, and if none fits, use a clearer method.

Signals in a problem statement and the technique each calls for
Signal in the statementWhat it usually meansTechnique
"Count the 1 bits" or "how many bits are set"Counting digits in binaryClear the lowest 1 bit in a loop, or count by column
"Every value appears twice except one"Matching pairs can cancelExclusive-or the whole list
"Is it a power of two"Exactly one 1 bitn & (n - 1) equals 0, for n above 0
"All subsets" of a small setA number from 0 up stands for each subsetLoop over masks, test bits
"No two chosen neighbors" in a maskNeighboring 1 bits are forbiddenmask & (mask >> 1) equals 0
"Maximum exclusive-or of two numbers"Choose the answer bit by bit from the topTest whether a partner exists

Pattern 1: count the 1 bits, by number or by column

One way to count 1 bits is to clear the lowest 1 bit until the number is 0, as above. A second way is to count by column, which scales to a range of numbers. Problem 1 asks for the total number of 1 bits in every whole number from 0 to 40. Writing the 41 numbers out is slow and error-prone. Instead count the 1s in each column. The lowest bit is 1 for every odd number, so it contributes one for every other number. The next bit repeats the pattern 0, 0, 1, 1, the next repeats in blocks of eight, and so on, with each column repeating twice as slowly as the one before. A column is easy to count for the complete blocks and then fix up for the partial block at the end. The cost is about one count per column, so O(log N) work for numbers up to N.

Pattern 2: exclusive-or cancels pairs

Because a number xor itself is 0, and xor does not care about order, the exclusive-or of a whole list cancels every value that appears twice and leaves the one that appears once. Problem 2 uses this on a list of nine values. It runs in one pass, with one running number, which is O(n) time and O(1) space. A dictionary of counts also works, in O(n) time, and costs O(n) space; saying both, and why the second is simpler to explain, is a good answer. The trick depends on the pairs, so check what the statement says about values that appear three times or not at all.

Pattern 3: a number as a set of positions

When a small set of items can be chosen or not, a number from 0 up to 2^n - 1 stands for each subset: bit i says whether item i is chosen. A loop over all the numbers visits every subset, and the operations above test and change it. Neighbor rules turn into one expression: a mask has two neighboring 1 bits exactly when mask & (mask >> 1) is not 0. Problem 3 counts the 10-digit masks with no neighboring 1 bits, which can also be counted by a short recurrence, and the two answers should agree.

Bit by bit is also a way to build an answer. For the largest exclusive-or of two numbers in a list, decide the answer from the top bit down, and at each position try to make that bit 1. A candidate is possible when two numbers in the list, looked at only down to that position, exclusive-or to it. To test that, keep those leading bits of every number in a set, then check whether the candidate exclusive-or one of them is also in the set. Problem 4 does this with a set, which turns "is there a partner" into one lookup. The cost is one pass per bit position, O(n) each, against O(n^2) for trying every pair.

Edge cases interviewers probe

  • Zero. It has no 1 bits, and the expression n & (n - 1) gives 0 for n = 0 even though 0 is not a power of two, so test n above 0 first.
  • Negative numbers. Languages differ in how they store them, so ask whether the input can be negative, and say what you assume.
  • The width. A shift can push a bit out of a fixed-size integer. Ask how many bits the numbers have.
  • Operator precedence. Mixing a bit operator with a comparison can group differently from what you expect, in some languages, so write the parentheses: (n & 1) == 1.
  • Shifting by a position that is too large. Say what you do when i is at or beyond the width.
  • Readability. If a clearer method has the same cost, say so, and use it.

A good habit is to write the numbers out in binary on paper for the smallest tricky case, and to trace the operation on them, before you call it done.

Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from counting 1 bits to the largest exclusive-or.

Problem 1. How many 1 bits are there in total when every whole number from 0 to 40 is written in binary? Give an integer.

Show the answer and the working

Answer: 102

  1. Count by bit position. The lowest bit is 1 for every odd number, so 20 of the numbers from 0 to 40 have it set. The next bit repeats the pattern 0, 0, 1, 1, so it is set for 20 numbers in 0 to 39, and 40 does not have it.
  2. The third bit repeats in blocks of eight, four numbers set per block, so 20 numbers from 0 to 39, and 40 does not have it. The fourth bit repeats in blocks of 16, with 8 set per block: 16 for 0 to 31, none in 32 to 39, and 40 (101000) sets it, for 17.
  3. The fifth bit (value 16) is set for 16 to 31, which is 16 numbers. The sixth bit (value 32) is set for 32 to 40, which is 9 numbers.
  4. The total is 20 + 20 + 20 + 17 + 16 + 9 = 102. Counting by column avoids writing out 41 numbers, and the cost is one count per bit position, O(log N) work for numbers up to N.

Problem 2. In the list 17, 4, 9, 4, 17, 23, 9, 12, 12, every value appears exactly twice except one, which appears once. Which value appears once? Give an integer.

Show the answer and the working

Answer: 23

  1. The exclusive-or of a number with itself is 0, and the exclusive-or of a number with 0 is the number. Exclusive-or does not care about order. So the exclusive-or of the whole list cancels every pair and leaves the single value.
  2. In order: 17 gives 17. 17 xor 4 gives 21. 21 xor 9 gives 28. 28 xor 4 gives 24. 24 xor 17 gives 9. 9 xor 23 gives 30. 30 xor 9 gives 23. 23 xor 12 gives 27. 27 xor 12 gives 23.
  3. The single value is 23.
  4. One pass with one running number is O(n) time and O(1) space. A dictionary of counts also works in O(n) time but needs O(n) space.

Problem 3. A mask is a whole number written with exactly 10 binary digits, leading zeros allowed, so it runs from 0 to 1023. How many masks have no two 1 bits next to each other? Give an integer.

Show the answer and the working

Answer: 144

  1. A mask has two neighboring 1 bits exactly when mask AND (mask shifted right by one) is not 0, so these are the masks where that value is 0. Count them with a recurrence on the length.
  2. Let a(n) be the number of n-digit strings with no two neighboring 1s. A string either ends in 0, after any valid string of n - 1 digits, or ends in 01, after any valid string of n - 2 digits. So a(n) = a(n - 1) + a(n - 2), with a(1) = 2 and a(2) = 3.
  3. The values for n = 1 to 10 are 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.
  4. The answer is 144. These counts are the Fibonacci numbers, and the same masks are the subsets of 10 items with no two neighbors, as in the house problem of the dynamic programming guide.

Problem 4. Of any two numbers in the list 5, 25, 3, 12, 18, 28, the exclusive-or of the two is computed. What is the largest value this can take over all pairs? Give an integer.

Show the answer and the working

Answer: 31

  1. Every number fits in 5 binary digits, so no exclusive-or can exceed 31 (11111). To reach 31, two numbers must differ in every one of the five bits, so one must be the bitwise complement of the other within 5 bits.
  2. Put the numbers in a set and test, for each number x, whether 31 xor x is in the set. For 5 it is 26, which is absent. For 25 it is 6, absent. For 3 it is 28, which is in the list.
  3. So 3 xor 28 = 31, which is binary 00011 and 11100 combining to 11111. No pair can beat 31, so the answer is 31.
  4. When 31 is not reachable, the method works from the top bit down: build the largest answer one bit at a time and test each candidate against the set of prefixes. That is O(n) per bit, against O(n^2) for trying every pair.

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

A short routine to practice

  1. Write the numbers in binary on paper before you code.
  2. Say which operation you need and what it does on one small example.
  3. State the cost: usually one pass, or one step per bit.
  4. Check zero, a power of two and an all-ones number.
  5. Say whether a clearer method is as fast.

Questions

When should I use bit manipulation in an interview?

Use it when a problem is about the binary digits of a number, when a number stands for a small set of items, or when exclusive-or can cancel matching pairs. Otherwise a clearer method is usually better.

What does exclusive-or do?

It gives 1 in a position where the two numbers have different bits and 0 where they have the same. So a number xor itself is 0, and a number xor 0 is the number.

How do I count the 1 bits in a number?

Repeatedly replace n with n and (n - 1), which clears the lowest 1 bit, and count the steps until n is 0. The loop runs once per 1 bit, not once per bit position.

How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: why a bit trick and not a dictionary, what the numbers look like in binary and which edge cases you checked. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms