Skip to main content

LeetCode Patterns

Bit Manipulation Pattern

The Bit Manipulation pattern treats integers as fixed-width arrays of bits and uses XOR, AND, OR, and shifts to solve counting, parity, and uniqueness problems in O(n) time and O(1) extra space. XOR's self-cancelling property finds the lonely element in a duplicate sea; masking with (x & (x - 1)) clears the lowest set bit in one step.

By Sam K., Founder, InterviewChamp.AI · Last verified

Complexity

Time
O(n)
Space
O(1)

When to use Bit Manipulation

  • Every element appears twice (or k times) except one — XOR across the array isolates the outlier in a single pass with no hash map.
  • You need to count set bits, check parity, or determine whether a number is a power of two using a constant-time bit trick.
  • The problem operates on subsets of a small (n <= 20) universe and you can encode each subset as an integer bitmask.
  • You need to swap, set, clear, or toggle a specific bit by index without touching the rest of the integer.
  • Arithmetic operators are forbidden by the problem (Sum of Two Integers) and you must simulate addition with XOR + carry shifts.

Template

function singleNumber(nums) {
  let result = 0;
  for (const num of nums) {
    result ^= num;
  }
  return result;
}

function countSetBits(x) {
  let count = 0;
  while (x !== 0) {
    x &= (x - 1);
    count++;
  }
  return count;
}

function setBit(x, i) { return x | (1 << i); }
function clearBit(x, i) { return x & ~(1 << i); }
function checkBit(x, i) { return (x >> i) & 1; }

Example LeetCode problems

#ProblemDifficultyFrequency
136Single Numbereasyfoundational
338Counting Bitseasyfoundational
371Sum of Two Integersmediumclassic
190Reverse Bitseasyfoundational
191Number of 1 Bitseasyfoundational
268Missing Numbereasyfrequently asked
137Single Number IImediumclassic
201Bitwise AND of Numbers Rangemediumless common

Common mistakes

  • Forgetting that JavaScript bitwise operators coerce to 32-bit signed integers, which silently overflows on values above 2^31 and breaks problems like Reverse Bits that expect 32 unsigned bits.
  • Writing `x & 1 == 0` instead of `(x & 1) === 0` — comparison binds tighter than bitwise AND in most languages, producing nonsense results.
  • Using `x % 2` for parity inside a tight loop and missing the faster `x & 1` trick that interviewers often want to see.
  • On Single Number II (every element three times except one), trying to apply XOR directly — XOR only cancels pairs, so the three-times variant needs a two-state counter or a bit-by-bit modular count.
  • Confusing logical right shift (`>>>` in JS) with arithmetic right shift (`>>`), which sign-extends and corrupts the high bits of a negative integer.

Frequently asked questions

Why does XOR find the single number in O(1) space?

XOR has three useful properties: a ^ a = 0, a ^ 0 = a, and it is commutative + associative. So XOR-ing the whole array pairs up every duplicate into zeros and leaves only the unique value standing. No hash map, no sorting, single pass.

What does `x & (x - 1)` actually do?

It clears the lowest set bit of x. Subtracting 1 flips the rightmost 1 and every zero below it; ANDing with the original zeroes them all. Calling it in a loop until x becomes zero counts the number of set bits in O(popcount) time — usually faster than checking each of 32 bits.

How do I add two numbers without using + or -?

XOR computes the sum without carry; AND followed by a left shift gives the carry. Loop: while carry is non-zero, replace a with a XOR b and b with (a AND b) << 1, until carry settles. Works for both positive and negative integers when you respect the 32-bit boundary.

When should I reach for a bitmask DP instead of a hash set?

Use a bitmask when the universe is small (n <= 20 or so) and you need to enumerate or remember subsets — the bitmask fits in a single integer, set operations are O(1), and you can index a DP table directly. For larger universes, the bitmask becomes too wide to be useful and a hash set is faster.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Related LeetCode patterns