👨‍💻 738LeetCode

Single Number

Question

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

Time requires O(N), memory O(1).

Example

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

Solution

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

Comment

Bit Manipulation XOR (^)