0

Bit Tricks

XOR cancels pairs, and-minus-one strips the lowest set bit, and shifts enumerate subsets.

Bit ManipulationO(1) or O(log n)New18 problems
18
mastery

Trigger phrases

If a problem statement sounds like one of these, try this pattern first.

single number
count set bits
power of two
subsets via masks

The template

Get this into muscle memory, then adapt the condition per problem.

let x = 0;
for (const n of nums) x ^= n;      // duplicates cancel
const lowest = x & -x;              // isolate lowest set bit
const count = () => { let c = 0; while (x) { x &= x - 1; c++; } return c; };

If you are stuck

The generic hint ladder for this pattern, in order.

  1. 1Every element appears twice except one. What operation cancels pairs?
  2. 2XOR is associative and commutative, so order does not matter.
  3. 3To split two unique numbers, partition by any bit where they differ.

Drill it

Every problem in the bank that uses this pattern.

0 / 18 solved
1
EBit Manipulation
2
EBit Manipulation
3
EBit Manipulation
4
EBit Manipulation
5
EBit Manipulation
6
MBit Manipulation
7
MBit Manipulation
8
9
EStrings
10
11
EBit Manipulation
12
MBit Manipulation
13
14
MBit Manipulation
15
16
MBit Manipulation
17
MBit Manipulation
18
MBit Manipulation