All problems
Single Number
Problem
Every element of nums appears exactly twice except for one element that appears once; return that unique value.
XOR all the numbers together so duplicate pairs cancel to 0 and the odd one out survives. Runs in O(n) time with O(1) extra space.
Hint
XOR is associative and commutative, so the order of cancellation does not matter.
Test cases
case 1
in: [[2,2,1]]
expected: 1
case 2
in: [[4,1,2,1,2]]
expected: 4
case 3
in: [[1]]
expected: 1
case 4
in: [[-1,-1,-2]]
expected: -2
case 5
in: [[0,0,5]]
expected: 5
Starter codePython
def single_number(nums):
# Your code here
pass5 test cases · run your code against them in the editor