←
Atlas · Finishing techniques · Topic 18 of 18

Bit Manipulation

Work on the binary digits directly: XOR cancels pairs, AND/shift count bits, all in O(1) space.

Spot it

Signals in the question

"Every number appears twice except one".

Counting 1 bits, powers of two, reversing bits.

Adding without +, or O(1) space where a set would be easy.

The idea

O(n) time · O(1) space

x ^ x = 0 and x ^ 0 = x, and XOR doesn't care about order. XOR all the numbers: every pair cancels out and only the single number is left.

Template · XOR cancels pairs

1def single_number(nums):2    result = 03    for x in nums:4        result ^= x   # pairs cancel: x ^ x = 05    return result

The template, filled in for Single Number. The highlighted line is the part every problem of this kind shares.

The best, free

One of each
WatchBit Manipulation, explainedNeetCode · YouTube · freeReadBit manipulationCP-Algorithms · free

Practice set

Loading your mission…

Common mistakes

1Forgetting operator precedence: x & 1 == 0 isn't (x & 1) == 0 in many languages.

2Right-shifting negative numbers: >> keeps the sign; JavaScript's >>> doesn't.

3Using bit tricks where a set would be clearer and fast enough.

Check yourself

Question 1 of 2

What is x & (x − 1)?