Leetcode 136 - Single Number

Problem Statement

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def singleNumber(self, nums):
"""
[2, 2, 1]
[010, 010, 001]
[4, 1, 2, 1, 2]
[0100, 0001, 0010, 0001, 0010]
"""
uniqueNumber = nums[0]
for i in range(1, len(nums)):
uniqueNumber ^= nums[i]
return uniqueNumber

This is an xor problem. If you have a list of number that are unsorted and you want to find the unique number, then xor all the numbers in the list and the final result will be the unique number. For example,

[2, 2, 1] is [010, 010, 001] so tracing through the code above:

1
2
3
4
5
6
7
010
010 xor
---
000
001 xor
---
001

or for [4, 1, 2, 1, 2]

1
2
3
4
5
6
7
8
9
10
11
12
13
0100
0001 xor
----
0101
0010 xor
----
0111
0001 xor
----
0110
0010 xor
----
0100 = 4