DSA AnimatorDSA animations
Single Number LC #136 Easy Bit Manipulation ยท XOR
Problem

Every element of nums appears twice except for one, which appears once. Find that single one, in linear time and using only constant extra space.

Example 1
Input: nums = [4,1,2,1,2]
Output: 4
Example 2
Input: nums = [2,2,1]
Output: 1
Constraints: 1 โ‰ค nums.length โ‰ค 3ยท10โด  |  each element appears twice except one
๐Ÿ”ข nums
0โ€“255 ยท up to 15 numbers ยท every value twice except one
bit = 1 ๐Ÿ”„ bit flipped by this XOR ๐Ÿ’ฅ value seen twice: its bits have cancelledโญ survivor
Variables
x
โ€”
acc
0
pairs cancelled
0
๐Ÿ’ก Step Logic
Press โ–ถ Play or Next to begin.
โœ“
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
acc = 0 (XOR's "nothing")
2
For every x: acc ^= x ๐Ÿ”„ flips the bits where x has a 1
3
Return acc: pairs have cancelled, the single number is left โญ
Time
O(n)
Space
O(1)
โŠ• XOR truth table
0^0=0
0^1=1
1^0=1
1^1=0

"Different โ†’ 1, same โ†’ 0". Each bit column of acc is just the parity (odd/even count) of the 1s seen in that column. Paired numbers add an even count, so only the single number's bits stay odd.

โš ๏ธ Edge cases & follow-ups

Works for negative numbers too (the sign bit cancels the same way). A HashSet also works but costs O(n) space, and sorting costs O(n log n). Related: 137 (every other number appears 3ร—: count bits mod 3) and 260 (two singles: split them by one differing bit).

How to solve Single Number

LeetCode 136 ยท Easy ยท Bit Manipulation ยท Pattern: XOR

Why the obvious approach is slow

A hash map of counts works, but it uses O(n) extra space. Sorting and scanning pairs takes O(n log n).

The key idea

Use the exclusive or operator, written as a caret. A number XOR itself is 0, and a number XOR 0 is the number itself. XOR is also order independent, so pairs can cancel no matter where they appear. XOR all the numbers together, and every pair cancels, leaving only the single one.

Remember

X XOR x is 0, and x XOR 0 is x. XOR everything, and pairs disappear.

Run the animation above on your own input, or watch the 1:31 video explanation of Single Number with a dry run and Java code.

More Bit Manipulation problems