Single Number Leetcode Solution Python

Question

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

You must implement a solution with a linear runtime complexity and use only constant extra space.

Solution (Python)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        xor = 0
        for num in nums:
            xor ^= num
        # a^a = 0 (each number a, when xor with itself is 0)
        # 0^b = b (hence, the final output will return the element which appears only once)
        return xor

Cracking the Coding Interview: 189 Programming Questions and Solutions

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.