Bit Manipulation Coding Problems: 83 Questions with Solutions
83 bit manipulation coding problems — 34 easy · 40 medium · 9 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 8-day plan.
- Problems: 83
- By difficulty: 34 easy · 40 medium · 9 hard
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
- Cost: Free on every plan; sign in to run and submit
Integers are strings of bits, and AND, OR, XOR and shifts read and write them directly. Counting set bits, finding the one number that appears once (XOR cancels pairs), testing a power of two, building subsets from a bitmask and reversing bits are the standard moves; the problems here practise them and the operator precedence and sign rules that make them go wrong.
How bit manipulation works, step by step
n = 44 (101100 in binary)- Count the 1 bits of 44 = 101100. Checking every position takes a step per bit; instead, n & (n − 1) deletes the lowest 1 bit in a single operation, so the loop runs once per 1 bit until n reaches 0.
- 44 − 1 = 43: subtracting 1 borrows from the lowest 1 bit (the 4s place), which becomes 0 while every 0 below it becomes 1. The bits above it are untouched.
- AND keeps a bit only where both rows have a 1: the higher bits survive and the flipped region is all 0s. 44 & 43 = 40 = 101000 — exactly one 1 bit is gone, so count = 1.
- Now n = 40 = 101000, whose lowest 1 bit is the 8s place, so 40 − 1 = 39 flips the 4 bits from there down. The bits above it are still untouched.
- The AND wipes the 4 flipped bits again: 40 & 39 = 32 = 100000, one fewer 1 bit, so count = 2.
- Now n = 32 = 100000, whose lowest 1 bit is the 32s place, so 32 − 1 = 31 flips the 6 bits from there down. No 1 bit sits above it any more.
- The AND wipes the 6 flipped bits again: 32 & 31 = 0 = 000000, one fewer 1 bit, so count = 3. Nothing is left, so the loop ends.
- n reached 0 after 3 rounds, so 44 has 3 set bits. The loop runs once per 1 bit — O(k) for k set bits instead of O(log n) for every bit — and the same trick tests for a power of two: n & (n − 1) == 0.
Bit Manipulation study plan
14 of the 83 Bit Manipulation problems (4 easy, 7 medium and 3 hard) over 8 days, about 8 h 10 min in all — the pattern first, then easiest to hardest. After that, the other 69 in the full list below are practice at your own pace. Then move on to Bitmask.
Day 1
Learn the pattern: read the essentials and step through the walkthrough above, then solve these 3.
- Number of 1 Bits Easy
- Single Number Easy
- Missing Number Easy
Day 2
Medium problems: the same pattern with one twist each. Name the twist before you code.
- Counting Bits Easy
- Sum of Two Integers Medium
Day 3
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Single Number II Medium
- Subsets Medium
Day 4
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Single Number III Medium
- Total Hamming Distance Medium
Day 5
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
Day 6
Hard problems: the pattern combined with a second idea. Give each a full attempt before reading the editorial.
Day 7
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Day 8
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Bit Manipulation: the essentials
When to reach for it
Values that fit a machine word with a question about their binary form; "every element appears twice except one"; a set of at most about 20 items whose subsets must all be tried (2²⁰ is about a million); flags packed into one integer; "add without the + and - operators".
The pattern
A handful of identities do most of the work. x & (x - 1) clears the lowest set bit and x & -x isolates it; x ^ x is 0 and x ^ 0 is x; (x >> i) & 1 reads bit i and x | (1 << i) sets it. XOR over a list cancels every value that appears an even number of times. Masks from 0 to (1 << n) - 1 enumerate every subset of n items, bit i saying whether item i is in.
def count_bits(n): # set bits of every value 0..n
ans = [0] * (n + 1)
for i in range(1, n + 1):
ans[i] = ans[i & (i - 1)] + 1
return ans
Cost
Bitwise operations are O(1) on a machine word; looping over bits is O(word size), and enumerating subsets is O(2ⁿ × n).
Common mistakes
- Precedence: in C, C++, Java and JavaScript,
==binds tighter than&, sox & 1 == 0does not test the low bit. Parenthesise every bitwise expression. - Shifting negatives:
>>keeps the sign in Java and JavaScript;>>>shifts in zeros. Python integers are unbounded, so mask with& 0xFFFFFFFFto imitate 32 bits. - JavaScript's bitwise operators work on 32-bit signed values, so
1 << 31is negative. 1 << 40overflows a 32-bitintin Java or C++; write1L << 40or1LL << 40.
Start with
- Single Number: XOR cancels the pairs.
- Counting Bits: popcounts built from smaller ones.
- Single Number II: counting bits modulo 3.
All bit manipulation problems
Easy (34)
- Number of Bit Changes to Make Two Integers Equal
- Find the XOR of Numbers Which Appear Twice Array, Hash Table
- Binary Watch Backtracking, Enumeration
- Smallest Number With All Set Bits Math
- Shortest Subarray With OR at Least K I Array, Sliding Window
- Maximum Strong Pair XOR I Array, Trie
- Complement of Base 10 Integer Math
- Find the K-or of an Array Array
- Number of Even and Odd Bits Math
- Rings and Rods Hash Table, String
- Sum of Values at Indices With K Set Bits Array
- Divide Array Into Equal Pairs Array, Hash Table
- Sum of All Subset XOR Totals Array, Math, Backtracking
- Count the Number of Consistent Strings Array, Hash Table, String
- Find the Difference Hash Table, String, Sorting
- Minimum Bit Flips to Convert Number
- Binary Number with Alternating Bits
- Decode XORed Array Array
- XOR Operation in an Array Math, Simulation
- Convert a Number to Hexadecimal Math
- Prime Number of Set Bits in Binary Representation Math
- Binary Gap
- Number Complement
- Power of Four Math, Recursion
- Hamming Distance
- Counting Bits Dynamic Programming
- Number of 1 Bits Divide and Conquer
- Sort Integers by The Number of 1 Bits Array, Sorting, Counting
- Set Mismatch Array, Hash Table, Sorting
- Number of Steps to Reduce a Number to Zero Math
- Add Binary Math, String, Simulation
- Power of Two Math
- Single Number Array
- Missing Number Array, Math
Medium (40)
- Minimum Number of Work Sessions to Finish the Tasks Array, Dynamic Programming, Bitmask
- Remove All Ones With Row and Column Flips Array, Matrix
- Minimum Impossible OR Array, Brainteaser
- Maximum OR Array, Greedy, Prefix Sum
- Minimum Array End Greedy
- Number of Wonderful Substrings Hash Table, String, Prefix Sum
- Bitwise ORs of Subarrays Array, Dynamic Programming
- Find the Longest Substring Containing Vowels in Even Counts Hash Table, String, Prefix Sum
- Longest Nice Subarray Array, Sliding Window
- UTF-8 Validation Array
- Maximum XOR for Each Query Array, Prefix Sum
- Count Number of Maximum Bitwise-OR Subsets Backtracking, Enumeration
- XOR Queries of a Subarray Array, Prefix Sum
- Decode XORed Permutation Array, Brainteaser
- Minimize XOR Greedy
- Flip String to Monotone Increasing String, Dynamic Programming
- Find the Xor-Beauty of Array Array, Math, Brainteaser
- Maximum XOR After Operations Array, Brainteaser
- Longest Subarray With Maximum Bitwise AND Array, Brainteaser
- Minimum Number of Operations to Make Array XOR Equal to K Array
- Find The Original Array of Prefix Xor Array, Prefix Sum
- Bitwise XOR of All Pairings Array, Brainteaser
- Integer Replacement Greedy, Dynamic Programming
- Minimum Operations to Reduce an Integer to 0 Greedy, Dynamic Programming
- Maximum Length of a Concatenated String With Unique Characters String, Backtracking
- Count Words Obtained After Adding a Letter String, Hash Table
- Number of Steps to Reduce a Number in Binary Representation to One String, Simulation
- Count Triplets That Can Form Two Arrays of Equal XOR Array, Hash Table, Math
- Divide Two Integers Math
- Concatenation of Consecutive Binary Numbers Math, Simulation
- Maximum Product of Word Lengths Array, String
- Minimum Flips to Make a OR b Equal to c
- Gray Code Math, Backtracking
- Maximum XOR of Two Numbers in an Array Array, Hash Table, Trie
- Sum of Two Integers Math
- Bitwise AND of Numbers Range
- Total Hamming Distance Array, Math
- Single Number III Array
- Single Number II Array
- Subsets Array, Backtracking
Hard (9)
- The Number of Good Subsets Array, Math, Dynamic Programming
- Minimum Incompatibility Array, Dynamic Programming, Bitmask
- Unique Paths III Array, Matrix, Backtracking
- Minimum Number of K Consecutive Bit Flips Array, Sliding Window, Prefix Sum
- Shortest Path Visiting All Nodes Breadth-First Search, Graph, Bitmask
- Count the Number of Square-Free Subsets Dynamic Programming, Bitmask, Math
- Maximum AND Sum of Array Dynamic Programming, Bitmask
- Find Subarray With Bitwise OR Closest to K Array, Binary Search, Segment Tree
- Minimum One Bit Operations to Make Integers Zero Math, Dynamic Programming
Companies that ask bit manipulation problems
- Amazon 77 problems on bit manipulation
- Google 55 problems on bit manipulation
- Adobe 24 problems on bit manipulation
- Meta 18 problems on bit manipulation
- Microsoft 13 problems on bit manipulation
- Apple 7 problems on bit manipulation
- TCS 6 problems on bit manipulation
- Uber 5 problems on bit manipulation
- Zoho 5 problems on bit manipulation
- Bloomberg 4 problems on bit manipulation
- Flipkart 3 problems on bit manipulation
- Cognizant 2 problems on bit manipulation
Next topic: Bitmask