Skip to content
Home Interview Bit Manipulation Interview Problems: Patterns, Tricks & Gotchas

Bit Manipulation Interview Problems: Patterns, Tricks & Gotchas

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Coding Patterns → Topic 9 of 17
Bit manipulation interview problems decoded — master XOR tricks, bitmask patterns, power-of-two checks, and Brian Kernighan's algorithm with runnable Java code.
🔥 Advanced — solid Interview foundation required
In this tutorial, you'll learn
Bit manipulation interview problems decoded — master XOR tricks, bitmask patterns, power-of-two checks, and Brian Kernighan's algorithm with runnable Java code.
  • XOR is your best friend for 'finding the odd one out' because $A \oplus A = 0$. Use it to achieve $O(1)$ space complexity.
  • The expression n & (n - 1) is a powerhouse—it flips the rightmost 1-bit to 0. It is the core of Brian Kernighan’s counting algorithm and power-of-two tests.
  • Bitwise operations are $O(1)$ at the CPU level, making them significantly faster than arithmetic operations in performance-critical code.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Imagine every number is secretly a row of light switches — each switch is either ON (1) or OFF (0). Bit manipulation is just flipping, checking, or combining those switches directly, without doing normal math. It's like adjusting Christmas lights one bulb at a time instead of replacing the whole string. Computers think in exactly this language, so when you work at the switch level, you skip all the middleman work and get blazing-fast results.

Every major tech company — Google, Meta, Amazon — consistently includes at least one bit manipulation problem in their coding rounds. That's not a coincidence. These problems test whether you understand how a CPU actually works at its lowest level, separating candidates who memorized patterns from those who genuinely understand computation. A single XOR or a bitwise AND can replace entire loops, cut memory usage in half, and run in constant time — and interviewers know it.

The core challenge with bit manipulation isn't the operators themselves — you likely know & | ^ ~ << >>. The challenge is pattern recognition: seeing a problem about finding a missing number or detecting duplicates and immediately knowing 'this is an XOR problem.' Without that pattern library wired into your brain, you'll stare at the problem and reach for a HashSet when a two-line XOR solution was sitting right there.

By the end of this article you'll have five rock-solid bit manipulation patterns locked in with real runnable code, you'll understand exactly why each trick works at the binary level (not just that it works), and you'll know the specific gotchas that cause smart engineers to get these wrong under interview pressure — things like signed integer overflow, arithmetic vs. logical right shifts, and why Brian Kernighan's bit-counting trick is faster than a naive loop.

The Power of XOR: Solving 'Single Number' (LeetCode 136)

The XOR (exclusive OR) operator is the 'magic wand' of bit manipulation. Its properties are unique: any number XORed with itself is 0 ($A \oplus A = 0$), and any number XORed with 0 is itself ($A \oplus 0 = A$). It is also commutative and associative.

In an interview, if you see a problem where every element appears twice except for one, don't reach for a Map or a Set. That's $O(n)$ space. By XORing every number in the array together, all pairs cancel each other out, leaving only the unique element. This is the gold standard for efficiency: $O(n)$ time and $O(1)$ space.

io/thecodeforge/bit/XorUniqueFinder.java · JAVA
12345678910111213141516171819202122
package io.thecodeforge.bit;

public class XorUniqueFinder {
    /**
     * Finds the element that appears only once in an array where
     * every other element appears exactly twice.
     */
    public int singleNumber(int[] nums) {
        int uniqueElement = 0;
        for (int currentNum : nums) {
            // XOR operation effectively 'cancels' out pairs
            uniqueElement ^= currentNum;
        }
        return uniqueElement;
    }

    public static void main(String[] args) {
        XorUniqueFinder finder = new XorUniqueFinder();
        int[] input = {4, 1, 2, 1, 2};
        System.out.println("The single number is: " + finder.singleNumber(input));
    }
}
▶ Output
The single number is: 4
🔥Forge Tip: XOR is order-independent
Because XOR is commutative, the numbers don't need to be adjacent. {1, 2, 1} and {1, 1, 2} both resolve to 2. This is why it works perfectly on unsorted arrays.

Counting Set Bits: Brian Kernighan’s Algorithm (LeetCode 191)

Interviewers often ask for the 'Hamming Weight' or the number of set bits (1s) in an integer. A naive approach checks every bit one by one ($O(32)$). However, Brian Kernighan’s algorithm is much faster because it only iterates as many times as there are set bits.

The trick lies in the expression n & (n - 1). This operation always flips the least significant (rightmost) set bit to zero. By repeating this until the number becomes zero, you count the bits in record time.

io/thecodeforge/bit/BitCounter.java · JAVA
1234567891011121314151617181920212223
package io.thecodeforge.bit;

public class BitCounter {
    /**
     * Counts the number of set bits (1s) in an integer.
     * Efficiency: O(k) where k is the number of set bits.
     */
    public int countSetBits(int inputNumber) {
        int count = 0;
        while (inputNumber != 0) {
            // This clears the least significant set bit
            inputNumber &= (inputNumber - 1);
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        BitCounter counter = new BitCounter();
        // Binary for 7 is 0111 (3 bits)
        System.out.println("Set bits in 7: " + counter.countSetBits(7));
    }
}
▶ Output
Set bits in 7: 3
⚠ Watch Out: The Power-of-Two Check
A direct application of this logic is checking if a number is a power of two. If (n & (n - 1)) == 0 (and $n > 0$), it's a power of two because powers of two have exactly one set bit.
OperationBitwise SyntaxCommon Interview Use Case
Check if Even/Odd(n & 1) == 0Faster than modulo operator (%)
Clear rightmost set bitn & (n - 1)Counting bits or Power-of-Two check
Isolate rightmost set bitn & -nUsed in Fenwick Trees or advanced grouping
Swap two numbersa ^= b; b ^= a; a ^= b;Classic 'no-extra-variable' swap trick
Check i-th bit(n >> i) & 1Building bitmasks or flags

🎯 Key Takeaways

  • XOR is your best friend for 'finding the odd one out' because $A \oplus A = 0$. Use it to achieve $O(1)$ space complexity.
  • The expression n & (n - 1) is a powerhouse—it flips the rightmost 1-bit to 0. It is the core of Brian Kernighan’s counting algorithm and power-of-two tests.
  • Bitwise operations are $O(1)$ at the CPU level, making them significantly faster than arithmetic operations in performance-critical code.
  • Always clarify with the interviewer if the integer is signed or unsigned, as this dictates whether you use the >>> or >> operator.

⚠ Common Mistakes to Avoid

    Forgetting operator precedence — In Java/C++, bitwise operators have lower precedence than comparison operators. `n & 1 == 0` is evaluated as `n & (1 == 0)`, which is wrong. Fix: Always use parentheses: `(n & 1) == 0`.
    Fix

    Always use parentheses: (n & 1) == 0.

    Ignoring signedness — The `>>` operator in Java is an 'arithmetic' shift that preserves the sign bit. For unsigned-style logic, you MUST use the `>>>` 'logical' shift operator to fill the left with zeros.

    with zeros.

    Integer Overflow — Performing a shift like `1 << 31` creates a negative value in a signed 32-bit integer. Always use `1L << 31` if you're working with larger bitmasks.

    r bitmasks.

Interview Questions on This Topic

  • QLeetCode 136: Single Number — Given a non-empty array of integers, every element appears twice except for one. Find that single one in O(1) space.
  • QLeetCode 190: Reverse Bits — Reverse bits of a given 32-bit unsigned integer using bitwise shifts.
  • QLeetCode 338: Counting Bits — Given an integer n, return an array of length n+1 such that ans[i] is the number of 1's in the binary representation of i.
  • QLeetCode 201: Bitwise AND of Numbers Range — Given a range [m, n], find the bitwise AND of all numbers in this range, inclusive.

Frequently Asked Questions

Why use bit manipulation instead of normal arithmetic?

Performance and space. Bitwise operations like (n >> 1) are often faster than (n / 2), and using a single int as a bitmask can represent 32 boolean flags, saving massive amounts of memory compared to a boolean array.

What is the difference between >> and >>> in Java?

The >> is an arithmetic shift; it maintains the sign bit (filling the left with 1s if the number is negative). The >>> is a logical shift; it always fills the left with 0s regardless of the sign.

Is bit manipulation still relevant in modern high-level languages?

Yes. It is critical for systems programming, cryptography, networking protocols, game engine optimization, and passing technical interviews at top-tier firms where efficiency is a core value.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousTwo Pointer Interview ProblemsNext →Stack and Queue Interview Problems
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged