Bit Manipulation
Expert Answer & Key Takeaways
Bit Manipulation: The Power of Binary
1. Essential Bitwise Operators
| Operator | Symbol | Rule |
|---|---|---|
| AND | & | 1 & 1 = 1, otherwise 0. (Masking) |
| OR | ` | ` |
| XOR | ^ | 1 ^ 0 = 1, 1 ^ 1 = 0. (Toggling/Canceling) |
| NOT | ~ | Flips all bits. |
| Left Shift | << | |
| Right Shift | >> | (Arithmetic) |
2. Common Bitwise Patterns
- Clear Rightmost Set Bit:
n & (n - 1)removes the least significant bit that is 1. - Extract Rightmost Set Bit:
n & -nisolates the lowest bit set to 1. - XOR Property: and . This is the basis for many "Single Number" problems.
3. Mental Model: Bitmasks
Single Number
nums, every element appears twice except for one. Find that single one.Examples
Level I: Brute Force (Frequency Map)
Intuition
Level II: Sorting
Intuition
Level III: Optimal (XOR Manipulation)
Intuition
Power of Two
n, return true if it is a power of two. Otherwise, return false.n is a power of two if there exists an integer x such that .Examples
Level I: Brute Force (Division)
Intuition
Level II: Math (Max Power of Two)
Intuition
n is a power of two, it must be a divisor of .Level III: Optimal (Bit Manipulation)
Intuition
n & (n - 1) clears the rightmost set bit. If n is a power of two, clearing its only set bit should result in 0.Single Number II
nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.Examples
Level I: Brute Force (Frequency Map)
Intuition
Level II: Sorting
Intuition
nums[i] is different from nums[i+1].Level III: Optimal (Bit Manipulation)
Intuition
Single Number III
nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.Examples
Level I: Brute Force (Frequency Map)
Intuition
Level II: Sorting
Intuition
Level III: Optimal (Bitwise Partitioning)
Intuition
Bitwise AND of Numbers Range
left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.Examples
Level I: Brute Force (Linear AND)
Intuition
left to right and perform bitwise AND on all numbers. This is slow if the range is large.Thought Process
- Initialize
res = left. - Iterate
ifromleft + 1toright. res &= i.- Return
res.
Pattern: Simulation
Level II: Iterative Shift (Pre-calculation)
Intuition
left and right rightward until they are identical. The bits that are removed are the ones that fluctuate within the range. Finally, shift the common prefix back to its original position.Level III: Optimal (Common Prefix / Brian Kernighan)
Intuition
Thought Process
- While
right > left:right = right & (right - 1)(clears the rightmost set bit).
- Alternatively, shift both numbers right until they are equal, then shift back.
Pattern: Bitwise Prefix Match
Detailed Dry Run
Number of 1 Bits
Examples
Level I: Brute Force (Iterate all 32 bits)
Intuition
Thought Process
- Initialize a counter
count = 0. - Loop 32 times (for a 32-bit integer):
- Check if the last bit is 1:
(n & 1) == 1. - If yes, increment
count. - Right shift by 1:
n >>= 1.
- Check if the last bit is 1:
- Return
count.
Pattern: Bitwise Iteration
Level II: Standard Library / Built-in
Intuition
POPCNT.Level III: Optimal (Brian Kernighan's Algorithm)
Intuition
n & (n - 1) always clears the least significant set bit of .Thought Process
- While :
- Set n = n \text{ & } (n - 1). This removes exactly one '1' bit.
- Increment
count.
- The number of iterations equals the number of set bits, which is more efficient for sparse numbers.
Pattern: Bit Manipulation Magic
Detailed Dry Run
| Iteration | n (Before) | n-1 | n & (n-1) | count |
|---|---|---|---|---|
| 1 | 1100 (12) | 1011 (11) | 1000 (8) | 1 |
| 2 | 1000 (8) | 0111 (7) | 0000 (0) | 2 |
| Result: 2 |
Reverse Bits
Examples
Level I: Brute Force (Iterate and Shift)
Intuition
Thought Process
- Initialize
res = 0. - Loop 32 times:
- Check the last bit of
n:n & 1. - Shift
resleft and add that bit:(res << 1) + (n & 1). - Right shift
nby 1.
- Check the last bit of
- Return
res.
Pattern: Bitwise Result Construction
Level II: Byte-by-Byte Lookup (Caching)
Intuition
Level III: Optimal (Divide and Conquer)
Intuition
Thought Process
- Swap bits 1-by-1:
n = ((n & 0xAAAAAAAA) >>> 1) | ((n & 0x55555555) << 1) - Swap bits 2-by-2:
n = ((n & 0xCCCCCCCC) >>> 2) | ((n & 0x33333333) << 2) - Swap bits 4-by-4:
n = ((n & 0xF0F0F0F0) >>> 4) | ((n & 0x0F0F0F0F) << 4) - Swap bits 8-by-8:
n = ((n & 0xFF00FF00) >>> 8) | ((n & 0x00FF00FF) << 8) - Swap bits 16-by-16:
n = (n >>> 16) | (n << 16)
Pattern: Parallel Bit Processing
Sum of Two Integers
a and b, return the sum of the two integers without using the operators + and -.Examples
Level I: Brute Force (Bit-by-Bit Simulation)
Intuition
Thought Process
- Initialize
res = 0,carry = 0. - For
ifrom 0 to 31:- Get -th bits of
aandb. sum = bitA ^ bitB ^ carry.carry = (bitA & bitB) | (carry & (bitA ^ bitB)).- Set -th bit of
restosum.
- Get -th bits of
- Return
res.
Pattern: Simulation / Logic Gates
Level II: Recursive XOR & AND
Intuition
a and b is equivalent to the XOR of a and b (sum without carry) plus the AND of a and b shifted left (the carry).Level III: Optimal (Iterative XOR & AND)
Intuition
a ^ b) and the carry itself ((a & b) << 1). We repeat this process until the carry becomes zero.Thought Process
a ^ bgives the sum bits where no carry is involved.a & bgives the bits where a carry is generated.- Shift the carry left by 1 to add it to the next significant bit.
- Repeat until carry is 0.
Pattern: Recursive Addition Logic
Detailed Dry Run
- Iteration 1: sum = 10 ^ 11 = 01 (1) carry = (10 & 11) << 1 = 100 (4)
- Iteration 2: sum = 001 ^ 100 = 101 (5) carry = (001 & 100) << 1 = 000 (0) Result: 5
Missing Number
nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.Examples
Level I: Brute Force (Sorting)
Intuition
nums[i] != i is the missing number. If all match, the missing number is .Thought Process
- Sort
numsin ascending order. - Iterate from to :
- If
nums[i] != i, returni.
- If
- If loop finishes, return
n.
Pattern: Sorting
Level II: Math (Sum Formula)
Intuition
Level III: Optimal (XOR)
Intuition
Thought Process
- Initialize
missing = n(or 0). - Iterate through the array:
missing ^= i ^ nums[i]
- Return
missing.
Pattern: XOR Cancellation
Detailed Dry Run
Count Triplets That Can Form Two Arrays of Equal XOR
arr. We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).a = arr[i] ^ ... ^ arr[j - 1] and b = arr[j] ^ ... ^ arr[k]. Return the number of triplets (i, j, k) such that a == b.Examples
Level I: Brute Force (O(N^3))
Intuition
i, j, and k. Calculate a and b for each triplet and check if they are equal.Thought Process
- Use three nested loops for
i,j, andk. - In the innermost loop, calculate XOR for
aandb. - If
a == b, incrementcount.
Pattern: Triple Nested Iteration
Level II: Prefix XOR with Hash Map
Intuition
Level III: Optimal (Prefix XOR)
Intuition
Thought Process
- Calculate prefix XOR array
prefix. - Iterate through all pairs where :
- If
prefix[i] == prefix[k+1]:- The number of valid
j's isk - i. - Add
k - itototal.
- The number of valid
- If
Pattern: Subarray XOR Frequency
Detailed Dry Run
- P[0] and P[3]: (i=0, k=2). count += 2-0 = 2 triplets.
- P[2] and P[5]: (i=2, k=4). count += 4-2 = 2 triplets. Total: 2 + 2 = 4.
Gray Code
- Every integer is in the inclusive range ,
- The first integer is 0,
- An integer appears no more than once in the sequence,
- The binary representation of every pair of adjacent integers differs by exactly one bit,
- The binary representation of the first and last integers differs by exactly one bit.
n, return any valid n-bit gray code sequence.Examples
Level I: Brute Force (Backtracking)
Intuition
Thought Process
- Start with 0.
- Try flipping each of the bits.
- If the result is not visited, move to it and recurse.
- If all bits visited, return the sequence.
Pattern: State Space Search
Level II: Reflected Construction (Iterative)
Intuition
Level III: Optimal (Bit Manipulation Formula)
Intuition
Thought Process
- The total number of elements is .
- For each index from 0 to :
- Calculate
i ^ (i >> 1).
- Calculate
- Add to result list and return.
Pattern: Formula-based Generation
Detailed Dry Run
- i=0: 0 ^ (0>>1) = 0 ^ 0 = 0 (00)
- i=1: 1 ^ (1>>1) = 1 ^ 0 = 1 (01)
- i=2: 2 ^ (2>>1) = 2 ^ 1 = 3 (11)
- i=3: 3 ^ (3>>1) = 3 ^ 1 = 2 (10) Result: [0, 1, 3, 2]
Repeated DNA Sequences
s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.Examples
Level I: Brute Force (Hash Set of Strings)
Intuition
Thought Process
- Use a
seenhash set to track substrings. - Use a
repeatedhash set to collect result strings. - Loop
ifrom 0 tos.length() - 10:- Extract substring
s.substring(i, i + 10). - If in
seen, add torepeated. - Else, add to
seen.
- Extract substring
Pattern: String Rolling Window
Level II: Rolling Hash (Rabin-Karp)
Intuition
Level III: Optimal (Bitmasking)
Intuition
Thought Process
- Map A=0, C=1, G=2, T=3.
- Maintain a 20-bit sliding window.
- Use a hash map/set to track encountered bitmasks.
Pattern: 2-bit Character Encoding
Maximum Product of Word Lengths
words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.Examples
Level I: Brute Force (Check All Pairs)
Intuition
Thought Process
- Nested loop for all pairs.
- For each pair:
- Check overlap: For char in word[i], is it in word[j]?
- If no overlap, update
maxProd.
Pattern: Double Iteration
Level II: Precomputed Sets
Intuition
Level III: Optimal (Bitmasking)
Intuition
Thought Process
- Precompute bitmasks for all words.
- Nested loop and check
(masks[i] & masks[j]) == 0. - Update max product.
Pattern: Alphabet Bitmasking
Detailed Dry Run
Maximum XOR of Two Numbers in an Array
nums, return the maximum result of nums[i] XOR nums[j], where .Examples
Level I: Brute Force (All Pairs)
Intuition
Thought Process
- Initialize
maxResult = 0. - Nested loop through
nums. maxResult = max(maxResult, nums[i] ^ nums[j]).- Return
maxResult.
Pattern: Double Iteration
Level II: Greedy Comparison with Hash Set
Intuition
Level III: Optimal (Binary Trie)
Intuition
Thought Process
- Insert all numbers into a Trie of depth 31.
- For each number :
- Start at the Trie root.
- For each bit of (from MSB to LSB):
- If we want bit and it exists in the Trie, move there and add to our current XOR.
- Else, move to the child with bit .
- Track the best XOR found for any .
Pattern: Bitwise Greedy with Trie
Divide Two Integers
dividend and divisor, divide two integers without using multiplication, division, and mod operator.Examples
Level I: Brute Force (Linear Subtraction)
Intuition
divisor from the dividend until the dividend becomes smaller than the divisor. The number of times we subtract is the quotient.Thought Process
- Handle edge cases (overflow for
INT_MIN). - Determine sign of result.
- Take absolute values of
dividendanddivisor. - Loop while
dividend >= divisor:dividend -= divisor.count++.
- Apply sign and return.
Pattern: Simulation
Level II: Recursive Long Division
Intuition
Level III: Optimal (Exponential Subtraction / Shifts)
Intuition
divisor at a time, we subtract the largest possible multiple of the divisor using bit shifts (divisor << k). This is equivalent to long division in binary.Thought Process
- While
dividend >= divisor:- Find the largest such that
divisor << k <= dividend. dividend -= (divisor << k).quotient += (1 << k).
- Find the largest such that
- This uses the property that is a fast way to find large chunks to subtract.
Pattern: Exponential Backoff / Long Division
Detailed Dry Run
- Largest shift: 3 << 2 = 12. 15 - 12 = 3. Quotient = 4 (2^2).
- Largest shift: 3 << 0 = 3. 3 - 3 = 0. Quotient = 4 + 1 = 5. Result: 5
Total Hamming Distance
nums.Examples
Level I: Brute Force (Check All Pairs)
Intuition
Thought Process
- Initialize
totalDist = 0. - For each pair where :
- Calculate Hamming distance:
Integer.bitCount(nums[i] ^ nums[j]). - Add to
totalDist.
- Calculate Hamming distance:
- Return
totalDist.
Pattern: Nested Iteration
Level II: Iterative Bit Verification
Intuition
Level III: Optimal (Bit Counting per Position)
Intuition
Thought Process
- Initialize
total = 0. - For each bit position to :
- Count numbers with -th bit set.
total += k * (n - k).
- Return
total.
Pattern: Positional Counting
Detailed Dry Run
Minimum Flips to Make a OR b Equal to c
a, b and c. Return the minimum flips required in some bits of a and b to make (a OR b == c).Examples
Level I: Brute Force (Bit-by-Bit Check)
Intuition
c with the current state a | b. Count the flips needed for each bit position.Thought Process
- For each bit position (0 to 31):
- If -th bit of
cis 0:- Both -th bits of
aandbmust be 0. Add their sum toflips.
- Both -th bits of
- If -th bit of
cis 1:- At least one of -th bits of
aorbmust be 1. If both are 0, add 1 toflips.
- At least one of -th bits of
- If -th bit of
- Return
flips.
Pattern: Positional Verification
Level II: Iterative with Built-in Counting
Intuition
Level III: Optimal (Bitwise Magic)
Intuition
(a | b) ^ c gives bits that are incorrect. We then handle the cases where c bit is 0 separately as they might require 2 flips per bit.Thought Process
incorrect = (a | b) ^ c.must_flip_two = a & b & incorrect.- Flips = Count of set bits in
incorrect+ Count of set bits inmust_flip_two.
Pattern: Composite Bitmasking
Detailed Dry Run
Sum of All Subset XOR Totals
nums.Examples
Level I: Brute Force (Backtracking)
Intuition
Thought Process
- Use recursion to explore including or excluding each element.
- Maintain a
currentXorvalue through the recursion tree. - Base case: If reached end of array, return
currentXor.
Pattern: Subset Generation
Level II: Iterative Subset Generation
Intuition
nums. For each mask, calculate the XOR total and add it to the sum.Level III: Optimal (Contribution of Each Bit)
Intuition
nums has the -th bit set, then in exactly half of the subsets (i.e., ), the XOR total will have the -th bit set. This is because adding a number with the -th bit set flips the -th bit of the XOR sum.Thought Process
- Find the bitwise OR of all numbers in the array. This identifies all bit positions that are set in at least one number.
- If the -th bit is set in the OR result, it contributes to the total sum.
- Result =
(OR of all nums) * 2^(n-1).
Pattern: Combinatorial Bit Counting
Detailed Dry Run
Reverse Pairs
nums, return the number of reverse pairs in the array. A reverse pair is a pair such that and .Examples
Level I: Brute Force (Nested Loops)
Intuition
Thought Process
- Use a nested loop .
- Check if .
- Return count.
Pattern: All-Pairs Comparison
Level II: Merge Sort based Counting
Intuition
Level III: Optimal (Binary Indexed Tree / Fenwick Tree)
Intuition
Thought Process
- Collect all and and sort them to create distinct ranks (Coordinate Compression).
- Iterate through
numsfrom right to left (or left to right with adjustments):- Query BIT for how many elements are strictly less than .
- Update BIT with .
- This leverages the bitwise structure of indices in the BIT.
Pattern: BIT with Coordinate Compression
Can I Win
maxChoosableInteger without reuse. The first to reach desiredTotal wins. Return true if the first player can force a win.Examples
Level I: Recursive Minimax (No Memoization)
Intuition
Thought Process
- Try choosing each available number .
- If , you win.
- Otherwise, if the other player cannot win from the state (remainder - , used numbers), you win.
- If no such exists, you lose.
Pattern: Game Theory Recursion
Level II: Recursion with Bitmask only
Intuition
Level III: Optimal (Bitmask DP / Memoization)
Intuition
maxChoosableInteger is at most 20, we can use a bitmask of length 20 to represent the set of used numbers. Memoizing the results of these masks drastically reduces the number of computations.Thought Process
- Use an integer
maskwhere the -th bit is 1 if number is used. - Store result of
canWin(mask)in a hash map or array. - Base cases:
desiredTotal <= 0or sum check.
Pattern: State Compression DP
Maximum AND Sum of Array
n integers into numSlots slots (max 2 per slot). The AND sum is the sum of (nums[i] & slotNumber). Return the maximum possible AND sum.Examples
Level I: Brute Force (Recursion)
Intuition
Level II: Greedy / Simple DP
Intuition
Level III: Bitmask DP (Ternary / Base-3)
Intuition
Thought Process
- Use a recursive function
solve(index, mask)whereindexis the current number innumswe are placing. - The
maskis a base-3 representation of slot occupancies. - For each slot :
- Check if slot has items.
- If yes, place
nums[index]in slot , update mask, and take the results.
Pattern: Base-N Bitmasking
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.