Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Bit Manipulation

Bit Tricks & Bitmasking

O(n)

XOR cancels pairs; x & (x−1) drops the lowest set bit; a mask enumerates subsets compactly.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksBitmask DPBinary Lifting & LCASparse Table (static RMQ)Binary (XOR) Trie+5
0%
mastery
0/55 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

"Every element appears twice except one", count set bits, power of two, add without +, or small subsets encoded as integer masks.

  1. 1Brute force

    Hash maps or arithmetic loops.

  2. 2The observation

    Extra memory/time: bits are processed in parallel and XOR is its own inverse.

  3. 3Why it works

    a ^ a = 0, a ^ 0 = a, XOR commutes, and each bit position is independent under XOR/AND/OR.

Reach for it when

  • +XOR cancellation — single number, missing number, two swapped values, find the duplicate.
  • +Counting / parity of bits — popcount, counting bits 0..n, powers of two.
  • +Encoding small sets as integer masks (also see Bitmask DP), or arithmetic without operators.

Not when

  • ×Large/continuous values where you need ranking or sumsuse Arrays or heaps
  • ×Set too big for a mask (>64 items to store, >~20 to enumerate 2ⁿ)use A real set
  • ×It looks numeric but needs ordering or searchuse Binary search or hashing
  • ×Arithmetic carries mix bits, so per-bit reasoning failsuse Ordinary arithmetic reasoning
  • ×You're enumerating subset states for an optimum under small nuse Bitmask DP

Intuition

Numbers are stored as bits — a row of on/off switches (powers of two). Bit tricks manipulate those switches directly, which is fast and sometimes the only O(1)-space way.

Read the full intuition

Four switches you must own:

  • XOR (^) — a "toggle." a ^ a = 0 (same thing twice cancels), a ^ 0 = a. XOR a whole list and every value appearing an even number of times vanishes — the odd-one-out survives. That's Single Number in one line.
  • AND (&) — masks/tests bits. x & 1 reads the lowest bit; x & (x-1) clears the lowest set bit (the heart of fast popcount).
  • OR (|) — sets bits. Shift (<<, >>) — multiply/divide by powers of two, or move a mask to bit b with 1 << b.

Walk Single Number on [4,1,2,1,2]: XOR running total goes 0→4→5→7→6→4. The two 1s cancel, the two 2s cancel, 4 remains.

Key idea

Most bit problems are one of: XOR cancellation (single/missing/swapped), per-bit counting (when duplicates come in 3s or k's, tally each bit mod k), or low-bit manipulation (x & -x isolates the lowest set bit; x & (x-1) clears it).

Why it costs what it costs

Time O(n) or O(32·n). XOR is a single pass; per-bit counting is 32 passes (constant factor); popcount is O(set bits).

Space O(1). a few integer accumulators — the whole appeal over hashing/sorting.

Practice

Next · Foundation

Number of 1 Bits

x &= x - 1 drops the lowest set bit.

0/55 solved
  • Number of 1 BitsFoundationFoundationAmazon, AdobeEasy
  • Single NumberApply it · Pairs cancel.Apply itAmazon, AdobeEasy
  • Power of TwoOne change · Single set bit test.One changeAdobe, AppleEasy
  • Counting BitsOne change · Bits for all numbers.One changeAmazon, AdobeEasy
  • Single Number IITwists · Triples instead of pairs.TwistsAmazon, CitadelMedium
  • Single Number IIIBranches · Two unique numbers.BranchesAmazon, CitadelMedium
  • Sum of Two IntegersBranches · No + operator.BranchesApple, AdobeMedium
  • Bitwise AND of Numbers RangeBranches · Range AND.BranchesAdobe, AmazonMedium
  • Maximum Product of Word LengthsCombine · Sets of letters as masks.CombineMedium
  • Counting BitsMastery checkMastery checkCSESMedium
  • Reverse BitsApple, AdobeEasy
  • Add BinaryMeta, AmazonEasy

Pitfalls

Classic bugs

  • !Width: JS bitwise is 32-bit signed (use >>>, | 0); Python ints are unbounded (mask & 0xFFFFFFFF).
  • !Precedence: x & 1 == 0 is x & (1==0). Write (x & 1) == 0.
  • !Right-shifting negatives is arithmetic (sign-filling) — use unsigned shift or mask first.
  • !Sum trick 2·sum(set) − sum(all) overflows and only fits 'exactly twice'; use XOR or per-bit counts (any k).
  • !x & (x-1) clears the lowest set bit; x & -x isolates it. Kernighan loops once per set bit, not 32.
  • !Single Number III: XOR all, split by the result's lowest set bit, XOR each group.
  • !Add without +: sum = a ^ b, carry = (a & b) << 1, repeat until carry is 0.
Go deepervariants and techniques · 9 combinations · interviewer follow-ups · resources

Variants and techniques

  • XOR Linear Basis (Gaussian elimination over GF(2))Reduce numbers to at most B independent vectors over GF(2) to answer max subset XOR, count distinct subset XORs, or membership.
  • Bitset OptimisationCP 2000Pack boolean DP rows or adjacency sets into machine words, so one AND/OR/shift handles 64 states at once. O(n*W) becomes O(n*W/64).
  • Few Distinct Subarray OR / AND / GCD ValuesInterview · hardFor a fixed right end i, the OR (AND, GCD) of a[j..i] changes at most log2(V) times as j moves left, because each change adds a bit (removes a bit, or at least halves the gcd). Keep the list of (value, leftmost j) for i - 1 and extend it to i.
  • XOR cancellationXOR the list; pairs vanish. Single Number, Missing Number.
  • Per-bit mod-k countingCount each bit position mod k for k-repeats. Single Number II.
  • Split by a differing bitXOR all, isolate a set bit, partition, XOR each half. Single Number III.
  • Low-bit tricksx&(x-1) clears, x&-x isolates — popcount, power-of-two tests. Number of 1 Bits, Power of Two.
  • Bit DP / arithmeticbits[i]=bits[i>>1]+(i&1); add via xor/carry. Counting Bits, Sum of Two Integers.

Combinations

  • Sum over Subsets (SOS) DP+Bit Tricks & Bitmasking

    for each x count y with x | y == x, x & y == y, or x & y == 0

    Sum over Subsets (SOS) DP:
    aggregates over submasks for all masks
    Bit Tricks & Bitmasking:
    mask representation

    SOS Bit ProblemCompatible Numbers

  • Backtracking+Bit Tricks & Bitmasking

    N-Queens, Sudoku, placement puzzles

    Backtracking:
    the search
    Bit Tricks & Bitmasking:
    O(1) constraint sets as bitmasks

    N-QueensSudoku SolverChessboard and Queens

  • Prefix Sum+Bit Tricks & Bitmasking+Hash Map / Hash Set Lookup

    substrings/subarrays where every letter (or bit) occurs an even number of times, or at most one is odd

    Prefix Sum:
    a substring's parity is prefix[j] ^ prefix[i]
    Bit Tricks & Bitmasking:
    a parity mask of the character counts replaces a count vector
    Hash Map / Hash Set Lookup:
    first index (or count) of each mask seen so far

    Find the Longest Substring Containing Vowels in Even CountsNumber of Wonderful SubstringsCount the Number of Beautiful Subarrays

  • Bitset Optimisation+Topological Sort

    for every vertex of a DAG with n ~ 5e4, the number of vertices reachable from it

    Bitset Optimisation:
    reach[v] = {v} | OR of reach[child], 64 vertices per word
    Topological Sort:
    process vertices in reverse topological order

    Reachable Nodes

  • Strongly Connected Components & Condensation+Topological Sort+Bitset Optimisation

    many 'can a reach b' queries on a general directed graph with n ~ 5e4

    Strongly Connected Components & Condensation:
    condense cycles so reachability lives on a DAG
    Topological Sort:
    an order for the DP over components
    Bitset Optimisation:
    per-component reachability sets

    Reachability Queries

  • Few Distinct Subarray OR / AND / GCD Values+Hash Map / Hash Set Lookup

    distinct subarray ORs, or the number of subarrays with AND equal to k

    Few Distinct Subarray OR / AND / GCD Values:
    at most log V distinct OR/AND values end at each index
    Hash Map / Hash Set Lookup:
    collect the distinct values, or count those equal to k

    Bitwise ORs of SubarraysNumber of Subarrays With AND Value of K

  • Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup

    the number of subarrays whose gcd equals x, for many x

    Few Distinct Subarray OR / AND / GCD Values:
    O(log V) (gcd, count) pairs per right end
    GCD / LCM & Euclid:
    the gcd as j moves left only drops to a divisor
    Hash Map / Hash Set Lookup:
    global count of subarrays per gcd value

    CGCDSSQNumber of Subarrays With GCD Equal to K

  • Bitset Optimisation+0/1 Knapsack

    which totals are reachable, values up to 5e4, n up to 5e4

    Bitset Optimisation:
    a shift-or over word-packed bits
    0/1 Knapsack:
    boolean reachability of sums

    Maximum Total Reward Using Operations II

  • Union-Find (Disjoint Set)+Bitset Optimisation+0/1 Knapsack

    split the vertices into two groups without breaking components, for every possible size

    Union-Find (Disjoint Set):
    component sizes
    Bitset Optimisation:
    makes the subset sum fast
    0/1 Knapsack:
    which totals of component sizes are achievable

    School Excursion

Follow-ups interviewers ask

  1. 01What if each number appears k times except one? → tally each bit count mod k (the state-machine variant).
  2. 02What if two numbers are unique? → XOR all, isolate a differing bit (d & -d), partition into two buckets, XOR each.
  3. 03Add two integers without +/-? → sum = a ^ b, carry = (a & b) << 1, repeat until carry is 0.
  4. 04Count set bits for every number 0..n efficiently? → DP: bits[i] = bits[i >> 1] + (i & 1) (Counting Bits).

State table

n binary running XOR x
— — 000 (0)
4 100 100 (4)
1 001 101 (5)
2 010 111 (7)
1 001 110 (6)
2 010 100 (4) → answer 4

Resources

  • Bit manipulationcp-algorithms · article
  • Bit Twiddling HacksSean Anderson · article
  • Binary cheatsheetTech Interview Handbook · article
  • <bit> headercppreference · docs
String Matching (KMP / Z / Rabin-Karp)Greedy
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial