Bit Manipulation Pattern: Template + 194 LeetCode Problems

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

  • 40 Easy
  • 96 Medium
  • 58 Hard
  • O(n) for a scan, O(2ⁿ) for subset enumeration time

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.

Bit Manipulation — Python 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.

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)

#ProblemDifficultyTopics
67Add BinaryEasyBit Manipulation, Math, String +1
136Single NumberEasyBit Manipulation, Array
190Reverse BitsEasyBit Manipulation, Divide and Conquer
191Number of 1 BitsEasyBit Manipulation, Divide and Conquer
222Count Complete Tree NodesEasyBit Manipulation, Tree, Binary Search +1
231Power of TwoEasyBit Manipulation, Recursion, Math
268Missing NumberEasyBit Manipulation, Array, Hash Table +3
338Counting BitsEasyBit Manipulation, Dynamic Programming
342Power of FourEasyBit Manipulation, Recursion, Math
389Find the DifferenceEasyBit Manipulation, Hash Table, String +1
401Binary WatchEasyBit Manipulation, Backtracking
405Convert a Number to HexadecimalEasyBit Manipulation, Math, String
461Hamming DistanceEasyBit Manipulation
476Number ComplementEasyBit Manipulation
645Set MismatchEasyBit Manipulation, Array, Hash Table +1
693Binary Number with Alternating BitsEasyBit Manipulation
266Palindrome PermutationPremiumEasyBit Manipulation, Hash Table, String
762Prime Number of Set Bits in Binary RepresentationEasyBit Manipulation, Math
832Flipping an ImageEasyBit Manipulation, Array, Two Pointers +2
868Binary GapEasyBit Manipulation
1009Complement of Base 10 IntegerEasyBit Manipulation
1018Binary Prefix Divisible By 5EasyBit Manipulation, Array
1342Number of Steps to Reduce a Number to ZeroEasyBit Manipulation, Math
1356Sort Integers by The Number of 1 BitsEasyBit Manipulation, Array, Counting +1
1486XOR Operation in an ArrayEasyBit Manipulation, Math
1684Count the Number of Consistent StringsEasyBit Manipulation, Array, Hash Table +2
1720Decode XORed ArrayEasyBit Manipulation, Array
1763Longest Nice SubstringEasyBit Manipulation, Hash Table, String +2
1863Sum of All Subset XOR TotalsEasyBit Manipulation, Array, Math +3
2032Two Out of ThreeEasyBit Manipulation, Array, Hash Table
2206Divide Array Into Equal PairsEasyBit Manipulation, Array, Hash Table +1
2220Minimum Bit Flips to Convert NumberEasyBit Manipulation
2351First Letter to Appear TwiceEasyBit Manipulation, Hash Table, String +1
2506Count Pairs Of Similar StringsEasyBit Manipulation, Array, Hash Table +2
2595Number of Even and Odd BitsEasyBit Manipulation
2859Sum of Values at Indices With K Set BitsEasyBit Manipulation, Array
2869Minimum Operations to Collect ElementsEasyBit Manipulation, Array, Hash Table
2917Find the K-or of an ArrayEasyBit Manipulation, Array
2932Maximum Strong Pair XOR IEasyBit Manipulation, Trie, Array +2
2980Check if Bitwise OR Has Trailing ZerosEasyBit Manipulation, Array

Medium (96)

#ProblemDifficultyTopics
29Divide Two IntegersMediumBit Manipulation, Math
78SubsetsMediumBit Manipulation, Array, Backtracking
89Gray CodeMediumBit Manipulation, Math, Backtracking
90Subsets IIMediumBit Manipulation, Array, Backtracking
137Single Number IIMediumBit Manipulation, Array
187Repeated DNA SequencesMediumBit Manipulation, Hash Table, String +3
201Bitwise AND of Numbers RangeMediumBit Manipulation
260Single Number IIIMediumBit Manipulation, Array
287Find the Duplicate NumberMediumBit Manipulation, Array, Two Pointers +1
318Maximum Product of Word LengthsMediumBit Manipulation, Array, String
371Sum of Two IntegersMediumBit Manipulation, Math
393UTF-8 ValidationMediumBit Manipulation, Array
397Integer ReplacementMediumGreedy, Bit Manipulation, Memoization +1
421Maximum XOR of Two Numbers in an ArrayMediumBit Manipulation, Trie, Array +1
464Can I WinMediumBit Manipulation, Memoization, Math +3
473Matchsticks to SquareMediumBit Manipulation, Array, Dynamic Programming +2
477Total Hamming DistanceMediumBit Manipulation, Array, Math
491Non-decreasing SubsequencesMediumBit Manipulation, Array, Hash Table +1
526Beautiful ArrangementMediumBit Manipulation, Array, Dynamic Programming +2
638Shopping OffersMediumBit Manipulation, Memoization, Array +3
672Bulb Switcher IIMediumBit Manipulation, Depth-First Search, Breadth-First Search +1
698Partition to K Equal Sum SubsetsMediumBit Manipulation, Memoization, Array +3
1318Minimum Flips to Make a OR b Equal to cMediumBit Manipulation
320Generalized AbbreviationPremiumMediumBit Manipulation, String, Backtracking
351Android Unlock PatternsPremiumMediumBit Manipulation, Dynamic Programming, Backtracking +1
751IP to CIDRPremiumMediumBit Manipulation, String
756Pyramid Transition MatrixMediumBit Manipulation, Hash Table, String +1
779K-th Symbol in GrammarMediumBit Manipulation, Recursion, Math
784Letter Case PermutationMediumBit Manipulation, String, Backtracking
861Score After Flipping MatrixMediumGreedy, Bit Manipulation, Array +1
898Bitwise ORs of SubarraysMediumBit Manipulation, Array, Dynamic Programming
957Prison Cells After N DaysMediumBit Manipulation, Array, Hash Table +1
1016Binary String With Substrings Representing 1 To NMediumBit Manipulation, Hash Table, String +1
1066Campus Bikes IIPremiumMediumBit Manipulation, Array, Dynamic Programming +2
1177Can Make Palindrome from SubstringMediumBit Manipulation, Array, Hash Table +2
1238Circular Permutation in Binary RepresentationMediumBit Manipulation, Math, Backtracking
1239Maximum Length of a Concatenated String with Unique CharactersMediumBit Manipulation, Array, String +1
1256Encode NumberPremiumMediumBit Manipulation, Math, String
1310XOR Queries of a SubarrayMediumBit Manipulation, Array, Prefix Sum
1371Find the Longest Substring Containing Vowels in Even CountsMediumBit Manipulation, Hash Table, String +1
1386Cinema Seat AllocationMediumGreedy, Bit Manipulation, Array +1
1404Number of Steps to Reduce a Number in Binary Representation to OneMediumBit Manipulation, String, Simulation
1442Count Triplets That Can Form Two Arrays of Equal XORMediumBit Manipulation, Array, Hash Table +2
1457Pseudo-Palindromic Paths in a Binary TreeMediumBit Manipulation, Tree, Depth-First Search +2
1461Check If a String Contains All Binary Codes of Size KMediumBit Manipulation, Hash Table, String +2
1506Find Root of N-Ary TreePremiumMediumBit Manipulation, Tree, Depth-First Search +1
1525Number of Good Ways to Split a StringMediumBit Manipulation, Hash Table, String +1
1558Minimum Numbers of Function Calls to Make Target ArrayMediumGreedy, Bit Manipulation, Array
1680Concatenation of Consecutive Binary NumbersMediumBit Manipulation, Math, Simulation
1734Decode XORed PermutationMediumBit Manipulation, Array
1738Find Kth Largest XOR Coordinate ValueMediumBit Manipulation, Array, Divide and Conquer +5
1829Maximum XOR for Each QueryMediumBit Manipulation, Array, Prefix Sum
1908Game of NimPremiumMediumBit Manipulation, Brainteaser, Array +3
1915Number of Wonderful SubstringsMediumBit Manipulation, Hash Table, String +1
1930Unique Length-3 Palindromic SubsequencesMediumBit Manipulation, Hash Table, String +1
1947Maximum Compatibility Score SumMediumBit Manipulation, Array, Dynamic Programming +2
1986Minimum Number of Work Sessions to Finish the TasksMediumBit Manipulation, Array, Dynamic Programming +2
2002Maximum Product of the Length of Two Palindromic SubsequencesMediumBit Manipulation, String, Dynamic Programming +2
2044Count Number of Maximum Bitwise-OR SubsetsMediumBit Manipulation, Array, Backtracking +1
2128Remove All Ones With Row and Column FlipsPremiumMediumBit Manipulation, Array, Math +1
2135Count Words Obtained After Adding a LetterMediumBit Manipulation, Array, Hash Table +2
2152Minimum Number of Lines to Cover PointsPremiumMediumBit Manipulation, Geometry, Array +5
2174Remove All Ones With Row and Column Flips IIPremiumMediumBit Manipulation, Breadth-First Search, Array +1
2184Number of Ways to Build Sturdy Brick WallPremiumMediumBit Manipulation, Array, Dynamic Programming +1
2212Maximum Points in an Archery CompetitionMediumBit Manipulation, Array, Backtracking +1
2275Largest Combination With Bitwise AND Greater Than ZeroMediumBit Manipulation, Array, Hash Table +1
2305Fair Distribution of CookiesMediumBit Manipulation, Array, Dynamic Programming +2
2317Maximum XOR After OperationsMediumBit Manipulation, Array, Math
2397Maximum Rows Covered by ColumnsMediumBit Manipulation, Array, Backtracking +2
2401Longest Nice SubarrayMediumBit Manipulation, Array, Sliding Window
2411Smallest Subarrays With Maximum Bitwise ORMediumBit Manipulation, Array, Binary Search +1
2419Longest Subarray With Maximum Bitwise ANDMediumBit Manipulation, Brainteaser, Array
2425Bitwise XOR of All PairingsMediumBit Manipulation, Brainteaser, Array
2429Minimize XORMediumGreedy, Bit Manipulation
2433Find The Original Array of Prefix XorMediumBit Manipulation, Array
2438Range Product Queries of PowersMediumBit Manipulation, Array, Prefix Sum
2505Bitwise OR of All Subsequence SumsPremiumMediumBit Manipulation, Brainteaser, Array +2
2527Find Xor-Beauty of ArrayMediumBit Manipulation, Array, Math
2546Apply Bitwise Operations to Make Strings EqualMediumBit Manipulation, String
2564Substring XOR QueriesMediumBit Manipulation, Array, Hash Table +1
2568Minimum Impossible ORMediumBit Manipulation, Brainteaser, Array
2571Minimum Operations to Reduce an Integer to 0MediumGreedy, Bit Manipulation, Dynamic Programming
2572Count the Number of Square-Free SubsetsMediumBit Manipulation, Array, Math +2
2588Count the Number of Beautiful SubarraysMediumBit Manipulation, Array, Hash Table +1
2657Find the Prefix Common Array of Two ArraysMediumBit Manipulation, Array, Hash Table
2680Maximum ORMediumGreedy, Bit Manipulation, Array +1
2683Neighboring Bitwise XORMediumBit Manipulation, Array
2708Maximum Strength of a GroupMediumGreedy, Bit Manipulation, Array +4
2741Special PermutationsMediumBit Manipulation, Array, Dynamic Programming +1
2749Minimum Operations to Make the Integer ZeroMediumBit Manipulation, Brainteaser, Enumeration
2802Find The K-th Lucky NumberPremiumMediumBit Manipulation, Math, String
2857Count Pairs of Points With Distance kMediumBit Manipulation, Array, Hash Table
2871Split Array Into Maximum Number of SubarraysMediumGreedy, Bit Manipulation, Array
2939Maximum Xor ProductMediumGreedy, Bit Manipulation, Math
2992Number of Self-Divisible PermutationsPremiumMediumBit Manipulation, Array, Math +4
2997Minimum Number of Operations to Make Array XOR Equal to KMediumBit Manipulation, Array

Hard (58)

#ProblemDifficultyTopics
691Stickers to Spell WordHardBit Manipulation, Memoization, Array +5
411Minimum Unique Word AbbreviationPremiumHardBit Manipulation, Array, String +1
465Optimal Account BalancingPremiumHardBit Manipulation, Array, Dynamic Programming +2
782Transform to ChessboardHardBit Manipulation, Array, Math +1
805Split Array With Same AverageHardBit Manipulation, Array, Math +2
810Chalkboard XOR GameHardBit Manipulation, Brainteaser, Array +2
847Shortest Path Visiting All NodesHardBit Manipulation, Breadth-First Search, Graph +2
864Shortest Path to Get All KeysHardBit Manipulation, Breadth-First Search, Array +1
943Find the Shortest SuperstringHardBit Manipulation, Array, String +2
980Unique Paths IIIHardBit Manipulation, Array, Backtracking +1
982Triples with Bitwise AND Equal To ZeroHardBit Manipulation, Array, Hash Table
995Minimum Number of K Consecutive Bit FlipsHardBit Manipulation, Queue, Array +2
996Number of Squareful ArraysHardBit Manipulation, Array, Hash Table +4
1125Smallest Sufficient TeamHardBit Manipulation, Array, Dynamic Programming +1
1178Number of Valid Words for Each PuzzleHardBit Manipulation, Trie, Array +2
1255Maximum Score Words Formed by LettersHardBit Manipulation, Array, Hash Table +5
1284Minimum Number of Flips to Convert Binary Matrix to Zero MatrixHardBit Manipulation, Breadth-First Search, Array +2
1349Maximum Students Taking ExamHardBit Manipulation, Array, Dynamic Programming +2
1434Number of Ways to Wear Different Hats to Each OtherHardBit Manipulation, Array, Dynamic Programming +1
1483Kth Ancestor of a Tree NodeHardBit Manipulation, Tree, Depth-First Search +4
1494Parallel Courses IIHardBit Manipulation, Graph, Dynamic Programming +1
1521Find a Value of a Mysterious Function Closest to TargetHardBit Manipulation, Segment Tree, Array +1
1542Find Longest Awesome SubstringHardBit Manipulation, Hash Table, String
1595Minimum Cost to Connect Two Groups of PointsHardBit Manipulation, Array, Dynamic Programming +2
1601Maximum Number of Achievable Transfer RequestsHardBit Manipulation, Array, Backtracking +1
1611Minimum One Bit Operations to Make Integers ZeroHardBit Manipulation, Memoization, Dynamic Programming
1617Count Subtrees With Max Distance Between CitiesHardBit Manipulation, Tree, Dynamic Programming +2
1655Distribute Repeating IntegersHardBit Manipulation, Array, Dynamic Programming +2
1659Maximize Grid HappinessHardBit Manipulation, Memoization, Dynamic Programming +1
1681Minimum IncompatibilityHardBit Manipulation, Array, Dynamic Programming +1
1707Maximum XOR With an Element From ArrayHardBit Manipulation, Trie, Array
1723Find Minimum Time to Finish All JobsHardBit Manipulation, Array, Dynamic Programming +2
1755Closest Subsequence SumHardBit Manipulation, Array, Two Pointers +3
1787Make the XOR of All Segments Equal to ZeroHardBit Manipulation, Array, Dynamic Programming
1799Maximize Score After N OperationsHardBit Manipulation, Array, Math +4
1803Count Pairs With XOR in a RangeHardBit Manipulation, Trie, Array
1815Maximum Number of Groups Getting Fresh DonutsHardBit Manipulation, Memoization, Array +2
1835Find XOR Sum of All Pairs Bitwise ANDHardBit Manipulation, Array, Math
1879Minimum XOR Sum of Two ArraysHardBit Manipulation, Array, Dynamic Programming +1
1938Maximum Genetic Difference QueryHardBit Manipulation, Depth-First Search, Trie +2
1994The Number of Good SubsetsHardBit Manipulation, Array, Hash Table +5
2035Partition Array Into Two Arrays to Minimize Sum DifferenceHardBit Manipulation, Array, Two Pointers +4
2151Maximum Good People Based on StatementsHardBit Manipulation, Array, Backtracking +1
2157Groups of StringsHardBit Manipulation, Union Find, String
2172Maximum AND Sum of ArrayHardBit Manipulation, Array, Dynamic Programming +1
2247Maximum Cost of Trip With K HighwaysPremiumHardBit Manipulation, Graph, Dynamic Programming +1
2306Naming a CompanyHardBit Manipulation, Array, Hash Table +2
2322Minimum Score After Removals on a TreeHardBit Manipulation, Tree, Depth-First Search +1
2354Number of Excellent PairsHardBit Manipulation, Array, Hash Table +1
2403Minimum Time to Kill All MonstersPremiumHardBit Manipulation, Array, Dynamic Programming +1
2732Find a Good Subset of the MatrixHardBit Manipulation, Array, Hash Table +1
2791Count Paths That Can Form a Palindrome in a TreeHardBit Manipulation, Tree, Depth-First Search +2
2835Minimum Operations to Form Subsequence With Target SumHardGreedy, Bit Manipulation, Array
2836Maximize Value of Function in a Ball Passing GameHardBit Manipulation, Array, Dynamic Programming
2897Apply Operations on Array to Maximize Sum of SquaresHardGreedy, Bit Manipulation, Array +1
2920Maximum Points After Collecting Coins From All NodesHardBit Manipulation, Tree, Depth-First Search +3
2935Maximum Strong Pair XOR IIHardBit Manipulation, Trie, Array +2
2959Number of Possible Sets of Closing BranchesHardBit Manipulation, Graph, Enumeration +2

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the bit manipulation problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.