DevPath

← All problems

Single Number

Easy bit-manipulation

Description

Every value appears twice except one. Return the value that appears once.

Constraints

1 <= n <= 100000

Examples

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

Output: 4

Hints (1)
  • XOR of a number with itself is zero, and XOR is commutative.

Solutions

XOR all values. · Time O(n) · Space O(1)

func singleNumber(nums []int) int {
    x := 0
    for _, n := range nums {
        x ^= n
    }
    return x
}

Create a free account to submit solutions, track progress and save problems.

Create account