An interactive visualization of the XOR bit manipulation technique. Watch how XOR properties elegantly find the single non-duplicate number by canceling out pairs.
Bit Manipulation LeetCode 136 โ Easynums, every element appears twice except for one.
Find that single one.fun singleNumber(nums: IntArray): Int { var result = 0 for (num in nums) result = result xor num return result}
The XOR operation has special properties that make it perfect for this problem: a โ a = 0 (any number XOR'd with itself equals zero) and a โ 0 = a (any number XOR'd with zero equals itself). Since XOR is also commutative and associative, all the duplicate pairs cancel out to zero, leaving only the single unique number.
result = 0 (XOR identity element)result ^= numnum ^ num = 0, effectively removing both from the resultresult is the single non-duplicate numberWe iterate through the array once, performing a constant-time XOR operation on each element. We only use a single variable to track the result, so space complexity is constant regardless of input size.