Skip to content
We areTOP 1%
DSA · Pro · Pattern 6 of 9

Bit Manipulation

12 problems.
Your progress0%
1st Visit
0/12
2nd Visit
0/12
Revise
0/12

About this pattern

Bit manipulation treats an integer as a vector of independent bits. The core tools are x & (x - 1) to clear the lowest set bit, x & -x to isolate it, XOR to cancel equal values, and shifts to build masks. Many problems become simple once each bit position is analysed separately: count how many numbers have a bit set, or notice that an operation preserves those counts. Prefix XOR values and parity masks turn subarray conditions into hash-map lookups. Signals include XOR, AND or OR in the statement, values up to 2^30, a demand for constant extra space, or parity conditions over a small alphabet. Per-bit solutions usually run in O(n log C).

bool hasBit(long long x, int b) { return (x >> b) & 1; }
long long lowBit(long long x) { return x & -x; }
int popcount(unsigned x) { return __builtin_popcount(x); }

// How many numbers have each bit set; then reason bit by bit
array<int, 31> bitCounts(const vector<int>& a) {
    array<int, 31> cnt{};
    for (int x : a)
        for (int b = 0; b < 31; b++)
            if ((x >> b) & 1) cnt[b]++;
    return cnt;
}

// Enumerate every non-empty submask s of mask:
// for (int s = mask; s > 0; s = (s - 1) & mask) { ... }

Problems

Bit Manipulation questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Single Number IILeetCodeMedium Solve Single Number II on LeetCode (opens in a new tab)
2Single Number IIILeetCodeMedium Solve Single Number III on LeetCode (opens in a new tab)
3Bitwise AND of Numbers RangeLeetCodeMedium Solve Bitwise AND of Numbers Range on LeetCode (opens in a new tab)
4Total Hamming DistanceLeetCodeMedium Solve Total Hamming Distance on LeetCode (opens in a new tab)
5Find the Longest Substring Containing Vowels in Even CountsLeetCodeMedium Solve Find the Longest Substring Containing Vowels in Even Counts on LeetCode (opens in a new tab)
6AGAGA XOOORRRCodeforcesMedium 1500Solve AGAGA XOOORRR on Codeforces (opens in a new tab)
7Data Structures FanCodeforcesMedium 1500Solve Data Structures Fan on Codeforces (opens in a new tab)
8Boboniu and Bit OperationsCodeforcesMedium 1600Solve Boboniu and Bit Operations on Codeforces (opens in a new tab)
9Bitwise ORs of SubarraysLeetCodeMedium Solve Bitwise ORs of Subarrays on LeetCode (opens in a new tab)
10AND, OR and square sumCodeforcesMedium 1700Solve AND, OR and square sum on Codeforces (opens in a new tab)
11Little Girl and Maximum XORCodeforcesMedium 1700Solve Little Girl and Maximum XOR on Codeforces (opens in a new tab)
12BitsCodeforcesMedium 1700Solve Bits on Codeforces (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account