Pattern 22 of 22

Bit Manipulation Pattern: Template + 194 LeetCode Problems

Use XOR, masks and the low-bit trick to replace whole data structures with an integer.

Easy
40
Medium
96
Hard
58

What the bit manipulation pattern is

Bit manipulation problems reduce to a handful of identities that are worth knowing cold. XOR is its own inverse and is commutative, so xor-ing an entire array cancels every value that appears twice and leaves the one that does not — no hash map, no extra space. `x & (x - 1)` clears the lowest set bit, which counts set bits in as many iterations as there are ones rather than thirty-two, and instantly tests for a power of two. `x & -x` isolates that lowest set bit instead of clearing it. The second, larger use is the bitmask as a set: an integer's bits stand for membership, so a subset of up to twenty elements fits in one machine word, subsets can be enumerated by counting from zero to 2ⁿ, and a dynamic programming state can be indexed by which items have been used. Python integers have no fixed width and no overflow, which removes a whole class of bugs but also means a shift left never wraps and negative numbers behave as if they had infinitely many leading ones.

When to use it

  • Every element appears a fixed number of times except one — XOR or per-bit counting finds it.
  • The problem is about set bits, powers of two, or a specific bit position.
  • n is at most about twenty and you need to iterate over subsets or track which items are used.
  • A boolean set must be stored and compared cheaply, as a dynamic programming key.

The bit manipulation template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 194 problems listed below.

PythonBit Manipulation template
def single_number(nums):
    """Pairs cancel under XOR, so the odd one out survives."""
    result = 0
    for value in nums:
        result ^= value
    return result

def count_set_bits(x):
    total = 0
    while x:
        x &= x - 1        # clears the lowest set bit, so this runs once per 1
        total += 1
    return total

Complexity characteristics

Time
O(n) for a scan, O(2ⁿ) for subset enumeration
Auxiliary space
O(1)

The XOR cancellation scan is one pass with a single accumulator: linear time, constant space, no hash map. Counting set bits with x & (x − 1) runs once per set bit rather than once per bit position, so it is O(popcount) instead of O(word size). Bitmask enumeration is O(2ⁿ) by definition and bitmask dynamic programming is O(2ⁿ·n), which is why these problems cap n at around twenty.

Eyes only

Meet the bit manipulation problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 194 bit manipulation LeetCode problems

Every problem in the library the bit manipulation pattern applies to, grouped by LeetCode's own difficulty rating. 173 of the 194 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (40)

Easy problems
No.Problem
0067Add Binary
0136Single Number
0190Reverse Bits
0191Number of 1 Bits
0222Count Complete Tree Nodes
0231Power of Two
0268Missing Number
0338Counting Bits
0342Power of Four
0389Find the Difference
0401Binary Watch
0405Convert a Number to Hexadecimal
0461Hamming Distance
0476Number Complement
0645Set Mismatch
0693Binary Number with Alternating Bits
0266Palindrome PermutationPremium
0762Prime Number of Set Bits in Binary Representation
0832Flipping an Image
0868Binary Gap
1009Complement of Base 10 Integer
1018Binary Prefix Divisible By 5
1342Number of Steps to Reduce a Number to Zero
1356Sort Integers by The Number of 1 Bits
1486XOR Operation in an Array
1684Count the Number of Consistent Strings
1720Decode XORed Array
1763Longest Nice Substring
1863Sum of All Subset XOR Totals
2032Two Out of Three
2206Divide Array Into Equal Pairs
2220Minimum Bit Flips to Convert Number
2351First Letter to Appear Twice
2506Count Pairs Of Similar Strings
2595Number of Even and Odd Bits
2859Sum of Values at Indices With K Set Bits
2869Minimum Operations to Collect Elements
2917Find the K-or of an Array
2932Maximum Strong Pair XOR I
2980Check if Bitwise OR Has Trailing Zeros

Medium (96)

Medium problems
No.Problem
0029Divide Two Integers
0078Subsets
0089Gray Code
0090Subsets II
0137Single Number II
0187Repeated DNA Sequences
0201Bitwise AND of Numbers Range
0260Single Number III
0287Find the Duplicate Number
0318Maximum Product of Word Lengths
0371Sum of Two Integers
0393UTF-8 Validation
0397Integer Replacement
0421Maximum XOR of Two Numbers in an Array
0464Can I Win
0473Matchsticks to Square
0477Total Hamming Distance
0491Non-decreasing Subsequences
0526Beautiful Arrangement
0638Shopping Offers
0672Bulb Switcher II
0698Partition to K Equal Sum Subsets
1318Minimum Flips to Make a OR b Equal to c
0320Generalized AbbreviationPremium
0351Android Unlock PatternsPremium
0751IP to CIDRPremium
0756Pyramid Transition Matrix
0779K-th Symbol in Grammar
0784Letter Case Permutation
0861Score After Flipping Matrix
0898Bitwise ORs of Subarrays
0957Prison Cells After N Days
1016Binary String With Substrings Representing 1 To N
1066Campus Bikes IIPremium
1177Can Make Palindrome from Substring
1238Circular Permutation in Binary Representation
1239Maximum Length of a Concatenated String with Unique Characters
1256Encode NumberPremium
1310XOR Queries of a Subarray
1371Find the Longest Substring Containing Vowels in Even Counts
1386Cinema Seat Allocation
1404Number of Steps to Reduce a Number in Binary Representation to One
1442Count Triplets That Can Form Two Arrays of Equal XOR
1457Pseudo-Palindromic Paths in a Binary Tree
1461Check If a String Contains All Binary Codes of Size K
1506Find Root of N-Ary TreePremium
1525Number of Good Ways to Split a String
1558Minimum Numbers of Function Calls to Make Target Array
1680Concatenation of Consecutive Binary Numbers
1734Decode XORed Permutation
1738Find Kth Largest XOR Coordinate Value
1829Maximum XOR for Each Query
1908Game of NimPremium
1915Number of Wonderful Substrings
1930Unique Length-3 Palindromic Subsequences
1947Maximum Compatibility Score Sum
1986Minimum Number of Work Sessions to Finish the Tasks
2002Maximum Product of the Length of Two Palindromic Subsequences
2044Count Number of Maximum Bitwise-OR Subsets
2128Remove All Ones With Row and Column FlipsPremium
2135Count Words Obtained After Adding a Letter
2152Minimum Number of Lines to Cover PointsPremium
2174Remove All Ones With Row and Column Flips IIPremium
2184Number of Ways to Build Sturdy Brick WallPremium
2212Maximum Points in an Archery Competition
2275Largest Combination With Bitwise AND Greater Than Zero
2305Fair Distribution of Cookies
2317Maximum XOR After Operations
2397Maximum Rows Covered by Columns
2401Longest Nice Subarray
2411Smallest Subarrays With Maximum Bitwise OR
2419Longest Subarray With Maximum Bitwise AND
2425Bitwise XOR of All Pairings
2429Minimize XOR
2433Find The Original Array of Prefix Xor
2438Range Product Queries of Powers
2505Bitwise OR of All Subsequence SumsPremium
2527Find Xor-Beauty of Array
2546Apply Bitwise Operations to Make Strings Equal
2564Substring XOR Queries
2568Minimum Impossible OR
2571Minimum Operations to Reduce an Integer to 0
2572Count the Number of Square-Free Subsets
2588Count the Number of Beautiful Subarrays
2657Find the Prefix Common Array of Two Arrays
2680Maximum OR
2683Neighboring Bitwise XOR
2708Maximum Strength of a Group
2741Special Permutations
2749Minimum Operations to Make the Integer Zero
2802Find The K-th Lucky NumberPremium
2857Count Pairs of Points With Distance k
2871Split Array Into Maximum Number of Subarrays
2939Maximum Xor Product
2992Number of Self-Divisible PermutationsPremium
2997Minimum Number of Operations to Make Array XOR Equal to K

Hard (58)

Hard problems
No.Problem
0691Stickers to Spell Word
0411Minimum Unique Word AbbreviationPremium
0465Optimal Account BalancingPremium
0782Transform to Chessboard
0805Split Array With Same Average
0810Chalkboard XOR Game
0847Shortest Path Visiting All Nodes
0864Shortest Path to Get All Keys
0943Find the Shortest Superstring
0980Unique Paths III
0982Triples with Bitwise AND Equal To Zero
0995Minimum Number of K Consecutive Bit Flips
0996Number of Squareful Arrays
1125Smallest Sufficient Team
1178Number of Valid Words for Each Puzzle
1255Maximum Score Words Formed by Letters
1284Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
1349Maximum Students Taking Exam
1434Number of Ways to Wear Different Hats to Each Other
1483Kth Ancestor of a Tree Node
1494Parallel Courses II
1521Find a Value of a Mysterious Function Closest to Target
1542Find Longest Awesome Substring
1595Minimum Cost to Connect Two Groups of Points
1601Maximum Number of Achievable Transfer Requests
1611Minimum One Bit Operations to Make Integers Zero
1617Count Subtrees With Max Distance Between Cities
1655Distribute Repeating Integers
1659Maximize Grid Happiness
1681Minimum Incompatibility
1707Maximum XOR With an Element From Array
1723Find Minimum Time to Finish All Jobs
1755Closest Subsequence Sum
1787Make the XOR of All Segments Equal to Zero
1799Maximize Score After N Operations
1803Count Pairs With XOR in a Range
1815Maximum Number of Groups Getting Fresh Donuts
1835Find XOR Sum of All Pairs Bitwise AND
1879Minimum XOR Sum of Two Arrays
1938Maximum Genetic Difference Query
1994The Number of Good Subsets
2035Partition Array Into Two Arrays to Minimize Sum Difference
2151Maximum Good People Based on Statements
2157Groups of Strings
2172Maximum AND Sum of Array
2247Maximum Cost of Trip With K HighwaysPremium
2306Naming a Company
2322Minimum Score After Removals on a Tree
2354Number of Excellent Pairs
2403Minimum Time to Kill All MonstersPremium
2732Find a Good Subset of the Matrix
2791Count Paths That Can Form a Palindrome in a Tree
2835Minimum Operations to Form Subsequence With Target Sum
2836Maximize Value of Function in a Ball Passing Game
2897Apply Operations on Array to Maximize Sum of Squares
2920Maximum Points After Collecting Coins From All Nodes
2935Maximum Strong Pair XOR II
2959Number of Possible Sets of Closing Branches

Bit Manipulation pattern FAQ

What is the bit manipulation pattern?

Bit manipulation problems reduce to a handful of identities that are worth knowing cold. XOR is its own inverse and is commutative, so xor-ing an entire array cancels every value that appears twice and leaves the one that does not — no hash map, no extra space.

How many LeetCode problems use the bit manipulation pattern?

This page lists 194 LeetCode problems that the bit manipulation pattern applies to: 40 Easy, 96 Medium and 58 Hard. 173 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the bit manipulation pattern?

O(n) for a scan, O(2ⁿ) for subset enumeration time and O(1) space. The XOR cancellation scan is one pass with a single accumulator: linear time, constant space, no hash map. Counting set bits with x & (x − 1) runs once per set bit rather than once per bit position, so it is O(popcount) instead of O(word size). Bitmask enumeration is O(2ⁿ) by definition and bitmask dynamic programming is O(2ⁿ·n), which is why these problems cap n at around twenty.

When should I use the bit manipulation pattern in an interview?

Every element appears a fixed number of times except one — XOR or per-bit counting finds it. The problem is about set bits, powers of two, or a specific bit position.

Which bit manipulation problem should I start with?

LeetCode 67. Add Binary is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to bit manipulation?

Dynamic Programming, Hash Map, Backtracking, Math and Number Theory. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.