Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Find the number which appears once in an array

Posted on July 14, 2022July 14, 2022 by admin

Overview

An array is given in which every element is present twice except one element. The objective is to find that element in constant extra space

Example 1

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

Example 2

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

The idea is to use XOR here. Here we will use two properties of XOR

  • XOR of a number with itself is 0
  • XOR of 0 and any number is that number

So the idea is to do an XOR of all the numbers in the array. The number that we obtain at the end will be the answer.

Program

Below is the program for the same

package main

import "fmt"

func singleNumber(nums []int) int {
	lenNums := len(nums)
	res := 0
	for i := 0; i < lenNums; i++ {
		res = res ^ nums[i]
	}

	return res
}

func main() {
	output := singleNumber([]int{2, 1, 2, 3, 3})
	fmt.Println(output)

	output = singleNumber([]int{1, 1, 4})
	fmt.Println(output)

}

Output:

1
4

Also, check out our system design tutorial series here – System Design Tutorial Series

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme