Skip to content
DSA in JavaScript
← All patterns

Bit Manipulation

0/14 solved

What it is

Work directly on the binary form of numbers with AND, OR, XOR and shifts. These are the fastest operations a CPU has.

Used for

Single number (XOR), counting bits, powers of two, subsets as bitmasks.
nums
4
1
2
1
2
running xor
0
·
·
·
·
·

Step 1 of 5

Goal: every number appears twice except one. Find the odd one out without extra memory. Trick: the XOR operation (^) turns two equal numbers into 0, and anything XOR 0 stays itself. So XOR everything together and the pairs vanish.

You see

  • Find the single or odd one out
  • Powers of two
  • Subset enumeration via masks
  • Constant-space tricks

Learn it in

Binary representation of floating-point numbersBit ManipulationIs a power of two

Template

const single = nums => nums.reduce((a, b) => a ^ b, 0); // pairs cancel under XOR

Practice problems