const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Patterns

Bit Manipulation Patterns for LeetCode Interviews

Bit manipulation is the "magic trick" category of LeetCode — a small set of bitwise operators that produce elegant O(1) space solutions to problems that seem impossible otherwise. Learn the 5 essential tricks and apply them confidently.

10 min read|

Bit manipulation: 5 tricks that solve problems in O(1) space

XOR, bitmasks, and the bitwise operators that make interviewers smile

Bit Manipulation: The Magic Tricks of LeetCode

Bit manipulation problems look like magic the first time you see them. Someone finds a missing number in an array without extra space, or isolates a unique element from millions of duplicates with a single pass. The solution is three lines long and runs in O(1) space. It feels like a trick — and in a way, it is.

The good news is that bit manipulation leetcode problems rely on a surprisingly small set of tricks. There are really only 5 bitwise patterns you need to know, and once you learn them, these problems become some of the easiest points in a coding interview. Most bit manipulation questions have short, elegant solutions that interviewers love to see.

This guide breaks down every bitwise operator, teaches you the 5 essential bit tricks, walks through the classic problems you will actually encounter, and gives you a clear practice strategy. By the end, XOR will feel as natural as a for loop.

Bitwise Operators Crash Course for Coding Interviews

Before diving into tricks, you need to be fluent in the 6 bitwise operators. These operate on individual bits of integers and form the foundation of every bit manipulation pattern. If you already know your operators, skip ahead — but a quick refresher never hurts.

AND (&) returns 1 only when both bits are 1. It is the go-to operator for masking — extracting specific bits from a number. OR (|) returns 1 when at least one bit is 1, making it perfect for setting bits. XOR (^) returns 1 when exactly one bit is 1, and it is the star of bitwise operations interview questions because of its unique cancellation property.

NOT (~) flips every bit, turning 0s into 1s and vice versa. Left shift (<<) moves bits left, effectively multiplying by 2 for each position shifted. Right shift (>>) moves bits right, dividing by 2. These shift operators are the reason bit manipulation can replace multiplication and division in performance-critical code.

  • AND (&): 1 & 1 = 1, all others = 0 — use for masking and checking if a bit is set
  • OR (|): 0 | 0 = 0, all others = 1 — use for setting specific bits to 1
  • XOR (^): same bits = 0, different bits = 1 — use for toggling and finding unique elements
  • NOT (~): flips all bits — use with AND for clearing specific bits
  • Left Shift (<<): multiply by 2^n — use for creating bit masks like 1 << k
  • Right Shift (>>): divide by 2^n — use for examining bits one at a time

The 5 Essential Bit Manipulation Tricks

Every bit manipulation leetcode problem you will encounter in interviews maps to one of these 5 tricks. Master them and you have a complete bit manipulation cheat sheet for coding interviews. Each trick has a specific use case and a set of problems it unlocks.

Trick 1: XOR for finding unique elements. XOR has two critical properties — a ^ a = 0 (any number XORed with itself cancels out) and a ^ 0 = a (XOR with zero is identity). This means if you XOR every element in an array where all elements appear twice except one, every duplicate pair cancels to zero and you are left with the unique element. This is the core of the single number problem.

Trick 2: n & (n - 1) to clear the lowest set bit. Subtracting 1 from a number flips the lowest set bit and all bits below it. ANDing with the original clears that lowest bit. This is the key to counting bits leetcode problems and checking powers of two — a power of 2 has exactly one set bit, so n & (n - 1) equals zero.

Trick 3: Shift operators for multiply and divide by 2. Left shifting by 1 doubles a number, right shifting by 1 halves it. Combined with AND to check the lowest bit (n & 1), you can iterate through every bit in a number. This pattern appears in reverse bits and binary conversion problems.

Trick 4: Bitmasks for subset generation. A number with k bits can represent all 2^k subsets of a k-element set. Each bit position corresponds to including or excluding an element. Iterating from 0 to 2^k - 1 generates every possible subset — a powerful technique for binary operations coding problems involving combinations.

Trick 5: Two's complement for negative numbers. In two's complement representation, -n is stored as ~n + 1. The expression n & (-n) isolates the lowest set bit of n, which is useful in advanced problems like Binary Indexed Trees. Understanding two's complement also prevents off-by-one errors when working with NOT operations.

💡

The XOR Superpower

XOR is the most useful bitwise operator for interviews — remember: a XOR a = 0 and a XOR 0 = a. This single property solves Single Number (#136), finds missing numbers, and detects duplicates in O(n) time, O(1) space.

Classic Bit Manipulation LeetCode Problems

Bit manipulation problems are rare in interviews — maybe 5 to 10 percent of questions — but they are easy points when they appear because most require just one trick applied correctly. Here are the 6 classic problems every candidate should know.

Single Number (#136) is the quintessential XOR trick leetcode problem. Given an array where every element appears twice except one, find the unique element. XOR all elements together — duplicates cancel and you are left with the answer in O(n) time and O(1) space. No hash set needed.

Number of 1 Bits (#191), also called Hamming Weight, asks you to count the set bits in an integer. The elegant approach uses n & (n - 1) in a loop — each iteration clears the lowest set bit, and you count iterations. This runs in O(k) time where k is the number of set bits, not the total bit width.

Counting Bits (#338) asks for the number of 1 bits for every number from 0 to n. The dynamic programming approach uses the relationship: the bit count of i equals the bit count of i & (i - 1) plus one. This builds the entire array in O(n) time using our Trick 2.

Reverse Bits (#190) asks you to reverse the 32 bits of an unsigned integer. Process each bit with right shift and AND, build the result with left shift and OR. This is Trick 3 in action — shift operators let you examine and construct bit patterns one position at a time.

Missing Number (#268) gives you n numbers from the range 0 to n with one missing. XOR every number with every index — all pairs cancel except the missing number and its index. Alternatively, XOR everything with the numbers 0 through n. Same trick as Single Number, different framing.

Power of Two (#231) is a one-liner: return n > 0 and n & (n - 1) equals 0. A power of 2 has exactly one set bit, and clearing it with Trick 2 gives zero. This is one of the most satisfying bit manipulation solutions because it replaces a loop with a single expression.

XOR Deep Dive: The Star of Bit Manipulation

If you learn only one bitwise operator deeply, make it XOR. The XOR trick leetcode problems are among the most commonly asked, and XOR's mathematical properties make it uniquely powerful for interview problems. Understanding why XOR works will help you recognize when to apply it.

XOR has four key properties. First, a ^ a = 0 — any value XORed with itself is zero. Second, a ^ 0 = a — XOR with zero is identity. Third, XOR is commutative: a ^ b = b ^ a. Fourth, XOR is associative: (a ^ b) ^ c = a ^ (b ^ c). Together, these mean order does not matter and duplicates cancel.

These properties solve more problems than you might expect. For Single Number (#136), XOR the entire array and duplicates vanish. For Missing Number (#268), XOR all values with indices 0 through n — everything cancels except the missing value. For detecting the single duplicate in a range, XOR works the same way.

Advanced XOR applications appear in problems like Single Number II (#137) where every element appears three times except one, and Single Number III (#260) where two elements appear once while everything else appears twice. These require combining XOR with bit masking to separate the unique elements — a beautiful extension of the basic trick.

ℹ️

Interview Frequency

Bit manipulation problems are rare in interviews (maybe 5-10% of questions) but they're easy points when they appear — most require just one trick applied correctly.

When Bit Manipulation Is the Right Choice

Knowing the tricks is half the battle — the other half is recognizing when a problem calls for bitwise operations interview techniques. Here are the signals that should make you reach for bit manipulation.

Constant space requirement is the strongest signal. When a problem explicitly asks for O(1) space and involves finding unique or missing elements, bit manipulation is almost always the intended approach. Power of 2 checks are another giveaway — any problem involving powers of 2 has an elegant bitwise solution.

Toggling states and flags is a natural fit for XOR. If you need to flip between two states, XOR with 1 does it in place. Subset enumeration problems where you need to generate all subsets of a set are classic bitmask territory. And any problem that mentions binary representation is hinting at bit manipulation.

However, do not use bit manipulation just to be clever. If a hash set solution is clearer and the interviewer did not ask for O(1) space, the readable solution wins. Bit manipulation can make code harder to understand for readers unfamiliar with the operators. Save bit tricks for when they are the obvious best choice or when space constraints demand it.

  • Use bit manipulation when: O(1) space is required, checking powers of 2, toggling states, generating subsets, or the problem mentions binary representation
  • Avoid bit manipulation when: a hash set or sorting solution is clearer, the interviewer values readability, or the bitwise approach adds complexity without improving performance
  • Interview tip: mention the bitwise solution as an optimization even if you code the hash set approach — it shows depth of knowledge

Practice Strategy for Bit Manipulation

Bit manipulation has a steep learning curve but a low ceiling — once you internalize the 5 tricks, the problem space is small enough to cover completely. Here is a structured approach to get comfortable with binary operations coding.

Start with Single Number (#136) and Power of Two (#231). These two problems use Trick 1 (XOR) and Trick 2 (n & n-1) respectively, and both have clean one-pass solutions. If you can solve these from memory, you already handle the majority of bit manipulation interview questions.

Next, tackle Number of 1 Bits (#191) and Counting Bits (#338). These reinforce Trick 2 and introduce the DP relationship between bit counts. Then move to Reverse Bits (#190) for shift operator practice and Missing Number (#268) for another XOR application.

Once you are comfortable with the classics, try Sum of Two Integers (#371) which implements addition using only bitwise operators — it is a great test of whether you truly understand how bits work. For advanced practice, Single Number II (#137) and Single Number III (#260) extend the XOR pattern in creative ways.

Use YeetCode flashcards to drill pattern recognition. Bit manipulation is a category where spaced repetition works exceptionally well because the tricks are simple but easy to forget if you do not review them. A quick flashcard review before your interview ensures the patterns are fresh.

⚠️

Readability Matters

Don't use bit manipulation just to be clever — if a hash set solution is clearer and the interviewer didn't ask for O(1) space, the readable solution wins. Save bit tricks for when they're the obvious best choice.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now