← All articles
13 min read

Bit Manipulation Interview Questions: 15 Tricks and Patterns

Most bit manipulation interview questions reuse the same fifteen operations. This guide shows each trick in binary, explains why it works, and maps it to the problems it solves.

Bit manipulation interview questions test whether you can solve problems by operating directly on the binary representation of integers using AND, OR, XOR, NOT, and shifts. Nearly all of them reduce to about fifteen reusable tricks, such as x & (x - 1) to clear the lowest set bit and a ^ a = 0 to cancel pairs. Learn those tricks in binary, and problems like Single Number, Counting Bits, and Subsets become short, predictable code.

This guide gives you the trick table, a binary walkthrough for each important one, and the interview problems each trick solves.

Key Takeaways

  • Fifteen operations cover most bit manipulation interview questions. Memorize them as pictures in binary, not as formulas.
  • x & (x - 1) clears the lowest set bit and x & -x isolates it. These two expressions drive counting, power-of-two checks, and Single Number III.
  • XOR is the pair-cancelling operator. If a problem says "every element appears twice except one," reach for XOR first.
  • Bitmasks turn subsets of up to about 20 items into integers, which makes subset enumeration and bitmask DP possible.
  • Language matters: Python has no fixed width, Java and JavaScript have >>>, and in C, C++, Java, and JavaScript x & 1 == 0 does not mean what you think.

What Are Bitwise Operators?

Bitwise operators are operators that act on each bit of an integer independently, instead of on the number as a whole. There are six you need for interviews.

OperatorSymbolRule per bitExample (5 = 0101, 3 = 0011)
AND&1 only if both bits are 10101 & 0011 = 0001 (1)
OR|1 if either bit is 10101 | 0011 = 0111 (7)
XOR^1 if the bits differ0101 ^ 0011 = 0110 (6)
NOT~Flips every bit~5 = -6 in two's complement
Left shift<<Moves bits left, fills with 00101 << 1 = 1010 (10)
Right shift>>Moves bits right0101 >> 1 = 0010 (2)

Two more ideas make everything else click.

Bit positions count from the right, starting at 0. In 1100 (12), bits 2 and 3 are set. 1 << i builds a number with only bit i set, which is how you target a single position.

Negative numbers use two's complement. To negate x, flip all bits and add 1. So -x equals ~x + 1, and that identity is the reason x & -x works. In 8 bits, 12 is 00001100 and -12 is 11110100.

If you want the bigger picture of where bit tricks sit among other techniques, the coding interview patterns cheat sheet covers all the major patterns side by side.

The 15 Essential Bit Tricks Table

This is the core of the guide. Each row lists the expression, what it does, a binary example, and the problems it typically solves.

#TrickExpressionBinary exampleProblems it solves
1Check bit i(x >> i) & 1x=1010, i=1: 0101 & 1 = 1Reverse Bits, Single Number II, UTF-8 Validation
2Set bit ix | (1 << i)1000, i=1: 1010Building masks, Subsets
3Clear bit ix & ~(1 << i)1010, i=3: 0010Bitmask DP transitions
4Toggle bit ix ^ (1 << i)1010, i=0: 1011Parity masks, Wonderful Substrings
5Is oddx & 10111: 1Counting Bits, fast parity
6Clear lowest set bitx & (x - 1)1100: 1000Number of 1 Bits, Power of Two
7Isolate lowest set bitx & -x1100: 0100Single Number III, Fenwick trees
8Power of twox > 0 and x & (x - 1) == 01000: true, 1010: falsePower of Two, Power of Four
9Count set bitsloop on trick 61011: 3 iterationsHamming Distance, Number of 1 Bits
10XOR cancela ^ a = 0, a ^ 0 = a0110 ^ 0110 = 0000Single Number, Missing Number, Find the Difference
11Low k bits mask(1 << k) - 1k=3: 0111Masking to 32 bits, full-set check in bitmask DP
12Multiply or divide by 2^kx << k, x >> k0011 << 2: 1100Divide Two Integers, binary search midpoints
13Set lowest unset bitx | (x + 1)1011: 1111Bit-pattern puzzles
14Enumerate submaskssub = (sub - 1) & maskmask=0101: 0101, 0100, 0001, 0000Subset DP, partition problems
15Opposite signs(a ^ b) < 05 and -3: trueDivide Two Integers, overflow checks

Once you see x & (x - 1) as "remove the rightmost 1," a whole group of problems stops being puzzles.

Walkthrough: why x & (x - 1) clears the lowest set bit

Take x = 12.

x       = 1100
x - 1   = 1011   (the lowest 1 becomes 0, the zeros below it become 1)
x & x-1 = 1000   (the tail cancels, higher bits survive)

Subtracting 1 always flips the lowest 1 and everything below it. AND keeps only bits that are 1 in both, so that whole tail disappears. A power of two has exactly one set bit, so removing it gives 0. That is the entire proof behind trick 8.

Walkthrough: why x & -x isolates the lowest set bit

x       = 00001100   (12)
~x      = 11110011
-x      = 11110100   (~x + 1)
x & -x  = 00000100   (4)

Adding 1 to ~x carries through its trailing ones and stops exactly at x's lowest set bit. Above that position, x and -x are opposites, so only the lowest set bit survives the AND.

Walkthrough: enumerating submasks

Starting from sub = mask = 1011 and applying sub = (sub - 1) & mask until it reaches 0 gives 1011, 1010, 1001, 1000, 0011, 0010, 0001, 0000. Subtracting 1 moves to the next smaller number, and ANDing with the mask drops any bits outside the mask. Running this for every mask of n bits costs O(3^n) in total, which is a useful number to quote when you explain complexity. The Big O notation cheat sheet covers why exponential bounds like 2^n and 3^n are acceptable only for small n.

XOR Patterns Interviewers Love

XOR is the operator that returns 1 when two bits differ and 0 when they match. Its useful properties are that it is commutative, associative, self-inverse (a ^ a = 0), and has 0 as its identity. Those four facts generate most XOR interview questions.

Pattern 1: cancel the pairs

Single Number (LeetCode 136) gives an array where every element appears twice except one.

def single_number(nums):
    result = 0
    for n in nums:
        result ^= n
    return result

Every pair XORs to 0, and the order does not matter, so only the unpaired value remains. O(n) time, O(1) space.

Pattern 2: XOR indices against values

Missing Number (LeetCode 268) asks for the one number missing from 0 to n. XOR every index and every value together, plus n. Each present number appears twice and cancels, so the result is the missing one. Find the Difference (LeetCode 389) is the same idea applied to characters.

Pattern 3: split by a differing bit

Single Number III (LeetCode 260) has two unpaired values. XOR of the whole array gives a ^ b, which is nonzero because a and b differ. Its lowest set bit marks a position where a and b disagree, so you split the array into two groups by that bit and XOR each group.

def single_number_iii(nums):
    diff = 0
    for n in nums:
        diff ^= n
    low = diff & -diff
    a = 0
    for n in nums:
        if n & low:
            a ^= n
    return [a, diff ^ a]

This combines trick 10 and trick 7, which is exactly why the table is worth learning.

Pattern 4: prefix XOR

Prefix XOR works like prefix sums. If p[i] is the XOR of the first i elements, then the XOR of the range from i to j is p[j + 1] ^ p[i]. XOR Queries of a Subarray (LeetCode 1310) and Count Triplets That Can Form Two Arrays of Equal XOR (LeetCode 1442) are direct applications.

A related move is using a parity mask as a hash map key. In Find the Longest Substring Containing Vowels in Even Counts (LeetCode 1371), you toggle one bit per vowel and look for the earliest index with the same mask.

Pattern 5: XOR with a trie

Maximum XOR of Two Numbers in an Array (LeetCode 421) inserts each number into a binary trie from the highest bit down, then greedily walks the opposite branch for every bit. It is the hardest common XOR problem and a good test of whether you can combine data structures with bit reasoning.

Bit problems are where interviews often stall: you know an O(1) space trick exists, but under pressure the exact expression will not come back. Our guide on what to do when stuck in a coding interview covers how to recover out loud without losing the round.

Blanking on which bit trick fits? TechScreen is an invisible real-time AI interview assistant that listens to the problem and suggests the right approach, from XOR cancellation to bitmask DP, while staying hidden from screen shares on Zoom, Google Meet, Teams, HackerRank, and CoderPad. Start with 3 free tokens.

Get started free →

Counting and Isolating Bits

Counting set bits, also called population count or Hamming weight, is one of the most asked bit manipulation interview questions. There are three approaches worth knowing.

Shift and check. Test the lowest bit, shift right, repeat. This runs once per bit position, so 32 iterations for a 32-bit integer.

Kernighan's algorithm. Repeatedly clear the lowest set bit. It loops once per set bit, which is faster for sparse numbers.

def count_bits(x):
    count = 0
    while x:
        x &= x - 1
        count += 1
    return count

Built-ins. Most languages ship a popcount (see the gotchas section), but be ready to write Kernighan's loop by hand.

Counting Bits for every number

Counting Bits (LeetCode 338) asks for the bit count of every number from 0 to n. Calling a popcount n times works, but the expected answer is a one-line DP.

def count_bits_range(n):
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = dp[i >> 1] + (i & 1)
    return dp

Shifting right drops the lowest bit, so the count of i equals the count of i >> 1 plus that dropped bit. An equally valid recurrence is dp[i] = dp[i & (i - 1)] + 1. If you want more practice building recurrences like this, the dynamic programming patterns guide walks through the standard families.

Other counting and isolating problems

  • Hamming Distance (461): count set bits of x ^ y. XOR marks every differing position.
  • Total Hamming Distance (477): for each bit position, count how many numbers have it set (k). That position contributes k * (n - k).
  • Reverse Bits (190): read bit i with trick 1 and write it into position 31 - i.
  • Bitwise AND of Numbers Range (201): the answer is the common binary prefix of left and right. Shift both right until equal, then shift back.
  • Single Number II (137): every value appears three times except one. Count how many numbers have each bit set and take the count modulo 3.

Bitmasks for Subsets

A bitmask is an integer where bit i represents whether item i is included in a set. With n items, the integers 0 through 2^n - 1 represent every possible subset exactly once.

Generating all subsets

Subsets (LeetCode 78) has a clean bitmask solution that avoids recursion entirely.

def subsets(nums):
    n = len(nums)
    result = []
    for mask in range(1 << n):
        result.append([nums[i] for i in range(n) if mask >> i & 1])
    return result

This is O(n * 2^n), the same as backtracking. The recursion and backtracking guide covers the recursive alternative and when it handles pruning better.

Bitmasks as fast sets

When the universe is small, such as 26 lowercase letters, a mask replaces a hash set. Maximum Product of Word Lengths (LeetCode 318) builds one 26-bit mask per word, then two words share no letters exactly when mask_a & mask_b == 0. Maximum Length of a Concatenated String with Unique Characters (LeetCode 1239) uses the same idea.

Bitmask DP

Bitmask DP is dynamic programming where part of the state is a bitmask recording which items have been used. It works when n is small, usually 20 or fewer, because 2^20 is about one million states.

Shortest Path Visiting All Nodes (LeetCode 847) is the classic example. The state is (current node, visited mask). BFS starts from every node with only its own bit set, each move ORs in the neighbor's bit, and the answer is the first distance at which the mask equals (1 << n) - 1.

Other bitmask DP problems to know:

  • Partition to K Equal Sum Subsets (698): state is the mask of used numbers.
  • Smallest Sufficient Team (1125): state is the mask of covered skills.
  • Travelling salesman style problems: dp[mask][last] is the cheapest way to visit the cities in mask and end at last.

The recognition signal is a tiny constraint like n <= 12, n <= 16, or n <= 20 paired with "visit all," "assign each," or "cover every."

Language-Specific Gotchas

Bit tricks are language-agnostic, but most bugs in bit rounds come from language details. If you have not picked one yet, see which language to use in a coding interview.

LanguageInteger widthPopcountWatch out for
PythonUnlimited precisionint.bit_count() (3.10+), bin(x).count("1")Negative numbers have infinite leading 1s; mask with 0xFFFFFFFF
Java32-bit int, 64-bit longInteger.bitCount, Long.bitCountUse >>> for unsigned right shift; shift counts are taken modulo 32 for int
C++Implementation-defined, usually 32-bit intstd::popcount (C++20, <bit>), __builtin_popcountShifting by the type's width or more is undefined behavior; 1 << 31 overflows signed int
JavaScriptOperands converted to 32-bit signedNone built in1 << 31 is negative; use >>> 0 to read as unsigned; use BigInt beyond 32 bits
GoFixed widths by typebits.OnesCount in math/bitsHas an extra &^ (AND NOT) operator

Operator precedence

In C, C++, Java, and JavaScript, &, ^, and | bind more loosely than ==. So x & 1 == 0 parses as x & (1 == 0), which is wrong. Always write (x & 1) == 0. Python is the exception: comparison operators bind more loosely than bitwise ones, so the expression behaves as intended there. Parentheses are free, so use them everywhere.

Python and Sum of Two Integers

Sum of Two Integers (LeetCode 371) asks you to add without +. The standard loop computes carry with a & b and the partial sum with a ^ b. In Java or C++ it terminates because the carry eventually shifts off the top of a 32-bit integer. In Python it can loop forever on negative inputs, because there is no top. The fix is to simulate 32 bits.

def get_sum(a, b):
    mask = 0xFFFFFFFF
    while b & mask:
        a, b = (a ^ b) & mask, ((a & b) << 1) & mask
    return a if a <= 0x7FFFFFFF else ~(a ^ mask)

The last line converts a 32-bit pattern with bit 31 set back into a negative Python integer. Expect a follow-up question about this if you interview in Python; the Python interview questions guide covers related integer behavior.

Right shift on negatives

Arithmetic right shift keeps the sign bit, so -8 >> 1 is -4 in Python, Java, and JavaScript, and in C++20 and later. It rounds toward negative infinity, which differs from integer division in Java and C++ for odd negatives: -7 >> 1 is -4, while -7 / 2 is -3. In Python, -7 // 2 is also -4, so the two agree there.

Bit Manipulation Practice Problems

Work through these in order: easy problems build the tricks, mediums combine them, and hards embed them in larger algorithms.

LevelProblemLeetCode #Main trick
EasySingle Number136XOR cancel
EasyNumber of 1 Bits191Clear lowest set bit
EasyPower of Two231x & (x - 1) == 0
EasyMissing Number268XOR indices and values
EasyCounting Bits338DP on i >> 1
EasyReverse Bits190Check and set bits
EasyHamming Distance461XOR then popcount
MediumSum of Two Integers371Carry with AND, sum with XOR
MediumSingle Number II137Per-bit count modulo 3
MediumSingle Number III260Isolate lowest set bit
MediumBitwise AND of Numbers Range201Common prefix
MediumSubsets78Mask enumeration
MediumMaximum Product of Word Lengths318Letter masks
MediumMaximum XOR of Two Numbers in an Array421Binary trie
MediumPartition to K Equal Sum Subsets698Bitmask DP
HardShortest Path Visiting All Nodes847BFS over masks
HardSmallest Sufficient Team1125Bitmask DP over skills

Five of these (Sum of Two Integers, Number of 1 Bits, Counting Bits, Missing Number, Reverse Bits) make up the binary section of the Blind 75 list. If you are choosing between curated lists, our comparison of Blind 75 vs NeetCode 150 vs Grind 75 explains how much bit practice each one includes.

How to practice

  1. Draw the binary. For every new problem, write out two or three small inputs in 4 or 8 bits before coding.
  2. Name the trick out loud. Saying "I'll clear the lowest set bit with x and x minus one" shows the interviewer you know why it works. The guide on how to think out loud in a coding interview has phrasing that helps here.
  3. Test negatives and zero. Most bit bugs hide in 0, -1, and the minimum integer.

Bit manipulation rarely fills an entire interview, but it often decides whether your answer uses O(1) space or fits the time limit. Learn the fifteen tricks as binary pictures and most of these problems become routine.

Want a second brain for your next coding round? TechScreen runs invisibly during Zoom, Google Meet, Teams, HackerRank, and CoderPad sessions and gives real-time hints for bit manipulation, XOR, and bitmask DP questions, including the 32-bit edge cases that trip up Python solutions. Try it with 3 free tokens.

Get started free →

Frequently Asked Questions

What are the most common bit manipulation interview questions?

The most frequently asked ones are Single Number, Missing Number, Number of 1 Bits, Counting Bits, Reverse Bits, Power of Two, and Sum of Two Integers. Five of these appear in the Blind 75 list. Harder rounds add Single Number III, Maximum XOR of Two Numbers in an Array, Bitwise AND of Numbers Range, and bitmask dynamic programming problems such as Shortest Path Visiting All Nodes or Smallest Sufficient Team.

What does x & (x - 1) do?

It clears the lowest set bit of x. Subtracting 1 flips the lowest 1 bit to 0 and turns every 0 below it into 1. ANDing with the original value wipes out that whole tail, so only the higher bits survive. For example, 12 is 1100 and 11 is 1011, so 12 & 11 is 1000, which is 8. The same expression powers Kernighan's bit counting loop and the power-of-two check.

Why does XOR solve the Single Number problem?

XOR has three properties that make it work: any number XORed with itself is 0, any number XORed with 0 is itself, and the order of XOR operations does not matter. When every value appears twice except one, XORing the entire array makes each pair cancel to 0, leaving only the unpaired value. It runs in O(n) time with O(1) extra space, which is exactly what interviewers ask for.

How do you handle negative numbers in Python bit manipulation?

Python integers have unlimited precision, so a negative number behaves as if it had an infinite run of leading 1 bits. Loops that shift right until x becomes 0 never end for negative x. When a problem assumes 32-bit integers, mask with 0xFFFFFFFF to keep 32 bits, then convert back by checking whether bit 31 is set and, if so, returning ~(x ^ 0xFFFFFFFF). Sum of Two Integers is the classic case.

When should I use bitmask dynamic programming?

Use bitmask DP when the state needs to record which items out of a small set have been used, and the set has roughly 20 or fewer elements. Each subset becomes an integer from 0 to 2^n - 1, so the state fits in an array. Typical signals are visiting all nodes, assigning tasks to people, covering all required skills, or partitioning into groups. Runtime is usually O(2^n * n) or O(2^n * n^2).

Are bit manipulation questions still asked at FAANG in 2026?

Yes, but usually as one part of a broader round rather than a standalone topic. Easy bit questions show up in phone screens and online assessments, and XOR or bitmask ideas often appear as the optimal step in array, subset, or DP problems. Companies with systems, embedded, or trading roles tend to ask more of them. Knowing the core tricks lets you reach the O(1) space solution interviewers expect.

How do I count set bits in each language?

Python 3.10 and later has int.bit_count(), and older versions can use bin(x).count('1'). Java has Integer.bitCount and Long.bitCount. C++20 adds std::popcount in the bit header, and GCC and Clang also offer __builtin_popcount. Go has bits.OnesCount in math/bits. JavaScript has no built-in, so you write Kernighan's loop. Interviewers may still ask you to implement it by hand.

Ready to use AI assistance in your next interview?

TechScreen is the invisible AI assistant trusted by engineers interviewing at Google, Meta, Amazon, and hundreds of other companies. Start with 3 free tokens — no credit card required.

Ace your next interview →