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).