Skip to main content

๐Ÿ”ข Bit Manipulation

One-line summary: Operate directly on bits โ€” XOR, AND, OR, shifts โ€” for elegant O(1) tricks that would otherwise require O(n) logic.


Diagramโ€‹

Bit Manipulation Overview Bit Manipulation GIF

๐ŸŽฏ Conceptโ€‹

Computers store integers as sequences of bits (binary digits). Bit manipulation works on these bits directly using bitwise operators, letting you replace whole loops with single, blazingly fast CPU instructions.

flowchart LR
A["Decimal 5"] --> B["Binary 0101"]
C["Decimal 3"] --> D["Binary 0011"]
B --> E{"Bitwise Op"}
D --> E
E -->|"AND &"| F["0001 = 1"]
E -->|"OR |"| G["0111 = 7"]
E -->|"XOR ^"| H["0110 = 6"]

Core Operatorsโ€‹

OperationSymbolExampleResultRule
AND&5 & 311 only if both bits are 1
OR|5 | 371 if either bit is 1
XOR^5 ^ 361 if bits differ
NOT~~5-6flips every bit
Left shift<<5 << 110multiply by 2แต
Right shift>>5 >> 12divide by 2แต (floor)

Key XOR properties: a^a=0, a^0=a, commutative, associative. These make XOR the go-to tool for "find the odd one out" problems.

Essential Bit Tricks (Cheat Sheet)โ€‹

GoalExpression
Check if i-th bit is set(n >> i) & 1
Set the i-th bitn | (1 << i)
Clear the i-th bitn & ~(1 << i)
Toggle the i-th bitn ^ (1 << i)
Turn off lowest set bitn & (n - 1)
Isolate lowest set bitn & (-n)
Check power of twon > 0 && (n & (n - 1)) === 0
Multiply / divide by 2n << 1 / n >> 1

โšก Time & Space Complexityโ€‹

OperationTimeSpaceNotes
Single bitwise op (&, |, ^, <<, >>)O(1)O(1)One CPU instruction
Count set bits (Brian Kernighan)O(k)O(1)k = number of set bits
Count set bits (naive scan)O(log n)O(1)Iterate over all bits
Iterate all subsets via bitmaskO(2โฟ)O(1)n = number of elements
Bitmask DPO(2โฟ ยท n)O(2โฟ)Classic TSP-style problems

Key Insight: Bit operations are constant time regardless of the value, which is why they turn many O(n) checks into O(1).


Common Patternsโ€‹

Find Single Numberโ€‹

const singleNumber = (nums) => nums.reduce((acc, n) => acc ^ n, 0);

Check Even/Oddโ€‹

const isEven = (n) => (n & 1) === 0;

Count Set Bits (Brian Kernighan)โ€‹

function countBits(n) {
let count = 0;
while (n > 0) {
n &= n - 1;
count++;
}
return count;
}

XOR Swapโ€‹

let a = 5,
b = 3;
a ^= b;
b ^= a;
a ^= b;

Power of Two Checkโ€‹

const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;

Pitfallsโ€‹

  • JS bitwise ops work on 32-bit signed integers โ€” large numbers get truncated
  • ~n = -(n+1) โ€” use >>> 0 to convert to unsigned if needed
  • XOR swap doesn't work if a and b point to the same variable

๐Ÿงช Worked Examplesโ€‹

Example 1: Missing Number (XOR)โ€‹

Given n distinct numbers in range [0, n], find the one missing.

function missingNumber(nums) {
let xor = nums.length; // start with n
for (let i = 0; i < nums.length; i++) {
xor ^= i ^ nums[i]; // cancel indices with values
}
return xor;
}
// Every present number cancels with its index; the missing one survives.
// Time: O(n), Space: O(1)

Example 2: Generate All Subsets (Bitmask)โ€‹

Enumerate the power set of an array of size n using bit masks.

function subsets(nums) {
const n = nums.length;
const result = [];
for (let mask = 0; mask < 1 << n; mask++) {
const subset = [];
for (let i = 0; i < n; i++) {
if (mask & (1 << i)) subset.push(nums[i]);
}
result.push(subset);
}
return result;
}
// Each of the 2^n masks encodes one subset (bit i => include nums[i]).
// Time: O(2^n * n), Space: O(1) extra (excluding output)

Example 3: Sum of Two Integers Without +โ€‹

Add two integers using only bitwise operations.

function getSum(a, b) {
while (b !== 0) {
const carry = (a & b) << 1; // bits that carry over
a = a ^ b; // add without carry
b = carry; // apply carry next round
}
return a;
}
// XOR adds bit-by-bit; AND<&lt;1 computes the carry. Repeat until no carry.
// Time: O(1) (fixed 32-bit width), Space: O(1)

Practice Problemsโ€‹

Easy Problemsโ€‹

ProblemDifficultySolution
LC 136 โ€” Single NumberEasy
LC 191 โ€” Number of 1 BitsEasy
LC 231 โ€” Power of TwoEasy
LC 268 โ€” Missing NumberEasy
LC 338 โ€” Counting BitsEasy
LC 342 โ€” Power of FourEasy
LC 389 โ€” Find the DifferenceEasy
LC 401 โ€” Binary WatchEasy
LC 405 โ€” Convert a Number to HexadecimalEasy
LC 461 โ€” Hamming DistanceEasy
LC 476 โ€” Number ComplementEasy
LC 693 โ€” Binary Number with Alternating BitsEasy
LC 762 โ€” Prime Number of Set BitsEasy
LC 832 โ€” Flipping an ImageEasy
LC 868 โ€” Binary GapEasy
LC 1009 โ€” Complement of Base 10 IntegerEasy
LC 1290 โ€” Convert Binary Number in a Linked List to IntegerEasy
LC 1342 โ€” Number of Steps to Reduce a Number to ZeroEasy
LC 1356 โ€” Sort Integers by The Number of 1 BitsEasy
LC 1486 โ€” XOR Operation in an ArrayEasy
LC 1720 โ€” Decode XORed ArrayEasy
LC 2220 โ€” Minimum Bit Flips to Convert NumberEasy
LC 2239 โ€” Find Closest Number to ZeroEasy
CC โ€” Little Elephant and Bits (LEBITS)Easy
CC โ€” Bit Difference (BITDIFF)Easy
CC โ€” Count Set Bits (CNTSETBIT)Easy
CC โ€” XOR Basics (XORBASIC)Easy

Medium Problemsโ€‹

ProblemDifficultySolution
LC 137 โ€” Single Number IIMedium
LC 190 โ€” Reverse BitsMedium
LC 201 โ€” Bitwise AND of Numbers RangeMedium
LC 260 โ€” Single Number IIIMedium
LC 287 โ€” Find the Duplicate NumberMedium
LC 318 โ€” Maximum Product of Word LengthsMedium
LC 371 โ€” Sum of Two IntegersMedium
LC 393 โ€” UTF-8 ValidationMedium
LC 421 โ€” Maximum XOR of Two Numbers in an ArrayMedium
LC 477 โ€” Total Hamming DistanceMedium
LC 645 โ€” Set MismatchMedium
LC 898 โ€” Bitwise ORs of SubarraysMedium
LC 1310 โ€” XOR Queries of a SubarrayMedium
LC 1318 โ€” Minimum Flips to Make a OR b Equal to cMedium
LC 1442 โ€” Count Triplets That Can Form Two Arrays of Equal XORMedium
LC 1521 โ€” Find a Value of a Mysterious Function Closest to TargetMedium
LC 1680 โ€” Concatenation of Consecutive Binary NumbersMedium
LC 1734 โ€” Decode XORed PermutationMedium
LC 1829 โ€” Maximum XOR for Each QueryMedium
LC 1835 โ€” Find XOR Sum of All Pairs Bitwise ANDMedium
CC โ€” XOR Engine (XORENG)Medium
CC โ€” AND OR Union (ANDORUN)Medium
CC โ€” Subset XOR (SUBSETXOR)Medium
CC โ€” Bit Manipulation Tricks (BITTRICK)Medium

Hard Problemsโ€‹

ProblemDifficultySolution
LC 51 โ€” N-QueensHard
LC 52 โ€” N-Queens IIHard
LC 115 โ€” Distinct SubsequencesHard
LC 1178 โ€” Number of Valid Words for Each PuzzleHard
LC 1255 โ€” Maximum Score Words Formed by LettersHard
LC 1542 โ€” Find Longest Awesome SubstringHard
LC 1659 โ€” Maximize Grid HappinessHard
LC 1707 โ€” Maximum XOR With an Element From ArrayHard
LC 1803 โ€” Count Pairs With XOR in a RangeHard
LC 1915 โ€” Number of Wonderful SubstringsHard
LC 2003 โ€” Smallest Missing Genetic Value in Each SubtreeHard
CC โ€” Complex Bit Operations (COMPLEXBIT)Hard
CC โ€” Bit Masking DP (BITMASKDP)Hard
CC โ€” Trie with XOR (TRIEXOR)Hard
CC โ€” Advanced Bitwise (ADVBIT)Hard

โ† Back to Home ยท ยฉ sparshjaswal