Single Number

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 in Go

func singleNumber(nums []int) int {
	count := make(map[int]int, (len(nums)/2)+1)
	result := 0

	for _, n := range nums {
		count[n]++

		c := count[n]
		if c == 1 {
			result += n
		} else {
			result -= n
		}
	}

	return result
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.