136. Single Number

Easy

Problem:

Except for one, all elements appear twice. Find the element that appears only once.

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

https://leetcode.com/problems/single-number/

What to learn:

Exclusive OR (XOR)

When applying Exclusive OR, or XOR, to decimal numbers, elements that appear twice are initialized to 0, and elements that appear only once retain their original value.

>>> 0 ^ 0
0
>>> 4 ^ 0
4
>>> 4 ^ 4
0

Solution:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        result = 0
        for num in nums:
            result ^= num
            print(result)
        return result

Last updated