Bit manipulation is a set of techniques that work directly on the binary representation of numbers. It shows up regularly in coding interviews, and a small number of ideas can solve a surprisingly wide range of problems, often with very little extra memory.
In this chapter, we'll start with the basics of binary numbers and the most important bitwise operators. Then we'll move on to some powerful techniques that can help us solve many coding problems more efficiently.
Before we start manipulating bits, let's understand how numbers are represented in binary.
In everyday life, we use the decimal number system, which has ten digits, from zero to nine. Computers, however, use binary, which has only two digits: zero and one. Each binary digit is called a bit.
Let's take the decimal number 13 as an example.
To convert it into binary, we repeatedly divide the number by two and record the remainder. We continue until the quotient becomes zero, then read the remainders from bottom to top.
For 13, this gives us 1101. Now, let's understand what this actually means.
In binary, each position represents a power of two. Bit positions are counted from right to left, starting at zero. So the values of these positions are 1, 2, 4, 8, 16, and so on.
For the number 13, the bits at positions zero, two, and three are set to one. That means its value is two to the power of zero, plus two to the power of two, plus two to the power of three:
In Java, an int uses 32 bits. So the number 13 is actually stored with leading zeros, followed by 1101:
For simplicity, we'll usually show only the relevant bits.
The key takeaway is that every integer has a binary representation, and bit manipulation allows us to work directly with its individual bits.
Bitwise operators work on the individual bits of their operands. AND, OR, and XOR compare two numbers bit by bit. NOT works on a single number. The shift operators move bits left or right.
You can try each operator on your own numbers here:
Loading simulation...
&)Our first bitwise operator is AND. In most programming languages, bitwise AND is represented by the ampersand symbol (&).
The AND operator compares two numbers bit by bit. At each position, the result is one only if both bits are one. Otherwise, the result is zero.
Let's take two numbers: 10 and 12. Their binary representations are 1010 and 1100.
Now, let's compare their bits from left to right:
So our result is 1000, which is eight in decimal.
Where is AND useful? A simple example is checking whether a number is even or odd. Remember, for odd numbers, the rightmost bit is always one. For even numbers, it's always zero.
So we can check whether a number is odd by performing a bitwise AND with one. Since the binary representation of one has only its rightmost bit set, this operation isolates the rightmost bit of our number. If the number is odd, the result is one. If it's even, the result is zero.
This also works for negative numbers in two's complement. In Java, n % 2 returns -1 for negative odd numbers, so checking n % 2 == 1 would give the wrong answer there, while (n & 1) != 0 does not.
We can use this same idea to check any individual bit, which we'll explore later in this chapter.
|)Next, we have the bitwise OR operator, represented by the vertical bar symbol (|).
The OR operator also compares two numbers bit by bit. At each position, the result is one if at least one of the corresponding bits is one. It returns zero only when both bits are zero.
Let's use the same two numbers: 10 and 12.
At each of the first three positions, at least one bit is one, so we get three ones. At the last position, both bits are zero, so we get zero. Our final result is 1110, which is 14 in decimal.
Where is OR useful? One common application is setting a particular bit to one. When we perform OR with one, the result is always one, regardless of the original bit. But when we perform OR with zero, the original bit stays unchanged.
So, by creating a number with only the desired bit set to one, we can use OR to turn on that specific bit without changing any other bits. This is especially useful when we want to store multiple boolean flags or states within a single integer.
^)XOR is one of the most useful bitwise operators in coding interviews. It's represented by the caret symbol (^), and it stands for exclusive OR.
It compares two numbers bit by bit and returns one when the corresponding bits are different. If both bits are the same, it returns zero.
Let's apply XOR to 10 and 12:
Comparing each bit, we get 0110, which is six in decimal.
XOR has two extremely useful properties:
a ^ a = 0. That's because every bit matches its corresponding bit.a ^ 0 = a.These two simple properties are the foundation of many coding interview problems.
Suppose we have an array containing [1, 2, 4, 1, 2]. Every number appears exactly twice, except four, which appears only once. Our task is to find that unique number.
Here's where XOR becomes really useful. If we XOR all the elements together, the duplicate numbers cancel each other out. The two ones produce zero. The two twos also produce zero. And we're left with four.
This works because XOR is both associative and commutative, meaning the order in which we combine the numbers doesn't affect the result. We can regroup the pairs however we like.
Here's how we can implement this in code:
We solved the problem in O(n) time using O(1) extra space. No additional data structures, such as a hash set to track the numbers we've seen, are needed.
This is a great example of how understanding a simple bitwise operator can help us solve a problem with just a few lines of code.
~)Our next operator is NOT, typically represented by the tilde symbol (~).
Unlike AND, OR, and XOR, which work with two numbers, NOT operates on a single number. It simply flips every bit. Every zero becomes one, and every one becomes zero.
For example, suppose we have the four-bit pattern 0101. Applying NOT flips all four bits, giving us 1010. Pretty straightforward, right?
But there's an important detail when working with integers. In many programming languages, integers are represented using a fixed number of bits, such as 32 or 64. And NOT flips every bit, not just the ones we're displaying.
Most modern systems represent signed integers using a format called two's complement. In this format, the leftmost bit is the sign bit: if it is one, the number is negative. Because of this, applying NOT to the integer five produces negative six.
In fact, for an integer n, the result of ~n is -(n + 1) under this representation.
The exact behavior can vary depending on the programming language and integer type. For example, Python integers have no fixed width, but ~5 still evaluates to -6 because Python treats negative numbers as if they had infinitely many leading ones.
For now, just remember that NOT flips every bit, including the sign bit when one is present, which is why the result can be negative. We'll use this operator shortly to clear a specific bit.
<<) and Right Shift (>>)So far, we've learned how to combine and flip bits. But what if we want to move them? That's where bitwise shift operators come in.
Left shift. The left shift operator is represented by two less-than symbols (<<). As the name suggests, it shifts all bits to the left by a specified number of positions, filling the empty positions on the right with zeros.
For example, consider the number five. Its binary representation is 0101.
If we shift it left by one position, we get 1010, which is ten in decimal. Notice that shifting five left by one position doubled its value. If we shift it left by two positions, we get 10100, which is twenty.
So, for non-negative integers, shifting left by one position is equivalent to multiplying by two, as long as the result doesn't overflow. More generally, shifting left by k positions is equivalent to multiplying by two to the power of k, provided the result fits.
Overflow is easy to hit. In Java, 1 << 31 sets the sign bit and produces Integer.MIN_VALUE, which is negative, not 2^31. Use 1L << 31 when you need the value as a positive long.
Right shift. The right shift operator is represented by two greater-than symbols (>>). As you might expect, it shifts bits to the right.
For example, twenty in binary is 10100. Shifting it right by two positions gives us 00101, which is five.
So, for non-negative integers, shifting right by one position is equivalent to integer division by two, rounding down.
Arithmetic vs. logical right shift. There's one important distinction when working with negative numbers. Some languages support two types of right shift: arithmetic and logical.
The exact operators and behavior depend on the programming language:
In C++, right-shifting a negative signed number was implementation-defined before C++20. Since C++20, it is an arithmetic shift.
For now, just focus on understanding how left and right shifts work. We'll explore signed integers and overflow in more detail when needed.
Now that we understand the basic bitwise operators, let's combine them to perform some useful operations.
Suppose we have the number thirteen. Its binary representation is 1101.
Let's say we want to check whether the bit at position two is set to one. Remember, bit positions start at zero from the right.
First, we create a bitmask by shifting one to the left by two positions. This gives us 0100, where only the bit at position two is set. Now, we perform a bitwise AND between our number and this mask.
Since both numbers have a one at position two, the result is non-zero. That tells us the bit is set.
More generally, to check whether the bit at position k is set, we perform a bitwise AND between n and one shifted left by k positions. If the result is non-zero, the bit is set. Otherwise, it's not.
Next, suppose we want to set a particular bit to one. For this, we can use OR. Remember, OR with one always gives us one, while OR with zero leaves the original bit unchanged.
So we create the same mask and perform a bitwise OR with our number. For example, setting bit one in thirteen changes its binary representation from 1101 to 1111. That's fifteen in decimal.
Now, what if we want to clear a bit, meaning change it from one to zero? For this, we combine AND with NOT.
k positions.One important detail here is that NOT flips all the bits of an integer, including the leading zeros. In Java, an int has thirty-two bits, so even though we're displaying only four bits, the actual mask contains thirty-two bits. And that's perfectly fine, because the AND operation still clears only our target bit.
For example, clearing bit two in thirteen gives us the binary number 1001, which is nine in decimal.
Finally, suppose we want to toggle a bit. If it's zero, we want to turn it into one. And if it's one, we want to turn it into zero.
For this, we use XOR. Remember, XOR with one flips a bit, while XOR with zero leaves it unchanged. So we can toggle any bit by performing XOR between our number and one shifted left by the target position.
For example, toggling bit two in thirteen changes its value from thirteen to nine. And toggling the same bit again brings it back to thirteen.
These four operations are worth practicing. Once you're comfortable checking, setting, clearing, and toggling individual bits, you'll have a solid foundation for solving many common bitmasking problems.
One thing to watch for: in Java, C++, C#, JavaScript, and TypeScript, 1 << k is a 32-bit int, so k must stay between 0 and 31. For 64-bit values, shift a 64-bit one instead, such as 1L << k in Java.
Let's now look at a classic coding interview problem: given an integer, determine whether it's a power of two.
For example, 1, 2, 4, 8, and 16 are all powers of two. But numbers like 6, 10, and 12 are not.
One way to solve this is to repeatedly divide the number by two and check whether we eventually reach one without a remainder. But there's a much simpler approach using bit manipulation.
Here's an interesting observation. Every positive power of two has exactly one set bit in its binary representation.
Now, let's see what happens when we subtract one from a power of two. Take eight as an example. Eight in binary is 1000. And seven is 0111. Notice that none of their set bits overlap. So when we perform a bitwise AND between eight and seven, the result is zero.
And this isn't just true for eight. For any positive power of two, performing a bitwise AND between the number and the number minus one always gives us zero. For a number that is not a power of two, at least one set bit survives:
This gives us a simple way to check whether a number is a power of two:
0 & -1 is 0.If both conditions are true, the number is a power of two. And that's it.
This solution takes constant time and constant extra space for a fixed-width integer.
Now, let's take the number 12 as an example. Its binary representation is 1100. If we subtract one, we get 11, which is 1011 in binary.
Now, let's perform a bitwise AND between these two numbers:
The result is 1000, which is eight in decimal.
Notice that the rightmost set bit in 12 has been cleared, while all the other bits remain unchanged. And this isn't just true for 12. For any positive integer, performing a bitwise AND between the number and the number minus one removes its rightmost set bit.
In other words, the expression n & (n - 1) clears the rightmost set bit.
When we subtract one from a binary number, its rightmost set bit becomes zero, and all the zeros to its right become ones. Everything to the left remains unchanged.
Now, when we perform AND with the original number, those newly created ones become zeros because the corresponding bits in the original number were zero. And since the rightmost set bit was also cleared, we're left with the original number minus its rightmost set bit.
Next, suppose we want to count the number of set bits in an integer. One approach is to check every bit individually, all 32 of them for an int. But we can do something more efficient.
Here is the loop on 13 (1101), which has three set bits:
The loop runs exactly once for every set bit. So instead of checking every bit, we only iterate over the bits that are actually set. This technique is often called Brian Kernighan's algorithm.
This means its time complexity is proportional to the number of set bits, while the extra space complexity is constant. For a fixed-width integer, such as a 32-bit integer, the loop can execute at most 32 times, making it constant time.
Many programming languages also provide built-in functions for counting set bits. They are usually faster than a hand-written loop, often compiling to a single CPU instruction, and they are clearer to read:
Use the built-in function in production code. The loop above is still worth knowing for interviews, especially when you are asked to count bits from scratch.
We've learned how to remove the rightmost set bit. But what if we want to isolate it instead? There's another useful bit manipulation technique for that.
Let's take the number 12 as an example. Its binary representation is 00001100, using eight bits.
Now, let's look at negative 12. In two's complement representation, we get a negative number by flipping all the bits and adding one.
So, negative 12 is represented as 11110100.
Now, let's perform a bitwise AND between 12 and negative 12:
The result is 00000100, which is four in decimal. The result contains only the rightmost set bit of our original number. All the other bits have been cleared.
And this isn't specific to 12. For any non-zero integer, performing a bitwise AND between the number and its negative isolates the rightmost set bit.
In two's complement, negating a number flips all its bits and adds one. Adding one turns the trailing ones of the flipped number back into zeros and carries into the position of the original rightmost set bit, setting it to one again.
This leaves the rightmost set bit unchanged while flipping all the bits to its left. The bits to its right are zero in both numbers.
So when we perform AND between the original number and its negative, only the rightmost set bit remains.
One edge case: in Java, -Integer.MIN_VALUE overflows back to Integer.MIN_VALUE. The expression still returns the correct answer there, because Integer.MIN_VALUE has only one set bit.
This technique is particularly useful in problems involving bit patterns, Binary Indexed Trees, and finding the position of the lowest set bit.
Let's look at another interesting application of bit manipulation: bitmasking.
Suppose we're building a system where users can have three permissions: read, write, and execute.
One way to represent these permissions is to use three separate boolean variables. But what if we could store all three using just a single integer? That's exactly what bitmasking allows us to do.
The idea is simple. We assign one bit to each permission:
So, the binary value 001 represents read permission, 010 represents write permission, and 100 represents execute permission.
Here is what each line does:
011.111, meaning all three permissions are enabled.111 to 101, removing write permission while keeping the other two unchanged.And that's the basic idea behind a bitmask. A bitmask is simply an integer where individual bits represent different states or properties. Each bit tells us whether something is enabled or disabled, selected or not selected, present or absent.
This technique is useful for permissions, feature flags, and many coding interview problems involving subsets.
Let's look at a simple example. Suppose we have three elements in an array: A, B, and C. We can use a three-bit integer to represent which elements are included in a particular subset, with bit zero for A, bit one for B, and bit two for C.
For example, 000 means no elements are selected. 101 means the first and third elements are selected. And 111 means all three elements are selected.
Since each bit can be either zero or one, three bits give us eight possible combinations. That means we can represent all eight subsets of our three-element array. More generally, with n bits, we can represent two to the power of n different subsets.
And here's where this becomes really useful. Instead of maintaining a separate boolean array to track which elements we've selected, we can represent that entire state using a single integer, as long as we have enough bits. A 32-bit integer can track up to 32 elements, and a 64-bit integer up to 64.
To visit every subset of n elements, we can simply count from 0 to 2^n - 1, because every number in that range is a different mask:
This is especially helpful in backtracking and dynamic programming problems where we need to efficiently track, compare, and update different combinations of selected elements. Bitmask DP is covered in its own chapter.
Let's quickly recap what we've learned.
We started by understanding how integers are represented in binary. Then, we explored the fundamental bitwise operators:
Next, we combined these operators to perform common operations like checking, setting, clearing, and toggling individual bits.
We also explored some powerful techniques commonly used in coding interviews.
Bit manipulation might feel a little confusing at first, especially because we're so used to working with decimal numbers. But once you start thinking in binary and understand how each operator affects individual bits, these patterns become much easier to recognize.
And the best way to build that intuition is through practice. Start with problems like Single Number, Power of Two, Number of 1 Bits, and Counting Bits. Try working through the binary representations by hand before writing any code. Focus on understanding why each technique works, rather than just memorizing the expressions.
10 quizzes