Find the element that appears once in an array where every other element appears twice - GeeksforGeeks

23 Sep, 2021
Given an array of integers. All numbers occur twice except one number which occurs once. Find the number in O(n) time & constant extra space.
Example : 
Input:  ar[] = {7, 3, 5, 4, 5, 3, 4}
Output: 7 
One solution is to check every element if it appears once or not. Once an element with a single occurrence is found, return it. Time complexity of this solution is O(n2).
A better solution is to use hashing. 1) Traverse all elements and put them in a hash table. Element is used as key and the count of occurrences is used as the value in the hash table. 2) Traverse the array again and print the element with count 1 in the hash table. This solution works in O(n) time but requires extra space.The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence. The idea is based on the following two facts. a) XOR of a number with itself is 0. b) XOR of a number with 0 is number itself.
Let us consider the above example.  
Let ^ be xor operator as in C and C++.

res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4

Since XOR is associative and commutative, above 
expression can be written as:
res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)  
    = 7 ^ 0 ^ 0 ^ 0
    = 7 ^ 0
    = 7 
Below are implementations of above algorithm. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the array// element that appears only once#include <iostream>using namespace std; int findSingle(int ar[], int ar_size)    {        // Do XOR of all elements and return        int res = ar[0];        for (int i = 1; i < ar_size; i++)            res = res ^ ar[i];         return res;    } // Driver codeint main()    {        int ar[] = {2, 3, 5, 4, 5, 3, 4};        int n = sizeof(ar) / sizeof(ar[0]);        cout << "Element occurring once is "             << findSingle(ar, n);        return 0;    }
// Java program to find the array// element that appears only onceclass MaxSum{    // Return the maximum Sum of difference    // between consecutive elements.    static int findSingle(int ar[], int ar_size)    {        // Do XOR of all elements and return        int res = ar[0];        for (int i = 1; i < ar_size; i++)            res = res ^ ar[i];             return res;    }     // Driver code    public static void main (String[] args)    {        int ar[] = {2, 3, 5, 4, 5, 3, 4};        int n = ar.length;        System.out.println("Element occurring once is " +                            findSingle(ar, n) + " ");    }}// This code is contributed by Prakriti Gupta
# function to find the once# appearing element in arraydef findSingle( ar, n):         res = ar[0]         # Do XOR of all elements and return    for i in range(1,n):        res = res ^ ar[i]         return res # Driver codear = [2, 3, 5, 4, 5, 3, 4]print "Element occurring once is", findSingle(ar, len(ar)) # This code is contributed by __Devesh Agrawal__
// C# program to find the array// element that appears only onceusing System; class GFG{    // Return the maximum Sum of difference    // between consecutive elements.    static int findSingle(int []ar, int ar_size)    {        // Do XOR of all elements and return        int res = ar[0];        for (int i = 1; i < ar_size; i++)            res = res ^ ar[i];             return res;    }     // Driver code    public static void Main ()    {        int []ar = {2, 3, 5, 4, 5, 3, 4};        int n = ar.Length;        Console.Write("Element occurring once is " +                            findSingle(ar, n) + " ");    }} // This code is contributed by nitin mittal.
<?php// PHP program to find the array// element that appears only once function findSingle($ar, $ar_size)    {                 // Do XOR of all        // elements and return        $res = $ar[0];        for ($i = 1; $i < $ar_size; $i++)            $res = $res ^ $ar[$i];         return $res;    }     // Driver code    $ar = array(2, 3, 5, 4, 5, 3, 4);    $n = count($ar);    echo "Element occurring once is "         , findSingle($ar, $n);          // This code is contributed by anuj_67.?>
<script> // JavaScript program to find the array// element that appears only once function findSingle(ar, ar_size)    {        // Do XOR of all elements and return        let res = ar[0];        for (let i = 1; i < ar_size; i++)            res = res ^ ar[i];         return res;    } // Driver code         let ar = [2, 3, 5, 4, 5, 3, 4];        let n = ar.length;        document.write("Element occurring once is "            + findSingle(ar, n));     // This code is contributed by Surbhi Tyagi </script>
Output: 
Element occurring once is 2
The time complexity of this solution is O(n) and it requires O(1) extra space.
Another approach: This is not an efficient approach but just another way to get the desired results. If we add each number once and multiply the sum by 2, we will get twice the sum of each element of the array. Then we will subtract the sum of the whole array from the twice_sum and get the required number (which appears once in the array).Array [] : [a, a, b, b, c, c, d] Mathematical Equation = 2*(a+b+c+d) – (a + a + b + b + c + c + d) 
In more simple words: 2*(sum_of_array_without_duplicates) – (sum_of_array) 
let arr[] = {7, 3, 5, 4, 5, 3, 4}
Required no = 2*(sum_of_array_without_duplicates) - (sum_of_array)
            = 2*(7 + 3 + 5 + 4) - (7 + 3 + 5 + 4 + 5 + 3 + 4) 
            = 2*     19         -      31 
            = 38 - 31
            = 7 (required answer)
As we know that set does not contain any duplicate element we will be using the set here.
Below is the implementation of above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to find// element that appears once#include <bits/stdc++.h> using namespace std; // function which find numberint singleNumber(int nums[],int n){    map<int,int> m;    long sum1 = 0,sum2 = 0;     for(int i = 0; i < n; i++)    {        if(m[nums[i]] == 0)        {            sum1 += nums[i];            m[nums[i]]++;        }        sum2 += nums[i];    }         // applying the formula.    return 2 * (sum1) - sum2;} // Driver codeint main(){    int a[] = {2, 3, 5, 4, 5, 3, 4};    int n = 7;    cout << singleNumber(a,n) << "\n";     int b[] = {15, 18, 16, 18, 16, 15, 89};     cout << singleNumber(b,n);    return 0;} // This code is contributed by mohit kumar 29
// Java program to find// element that appears onceimport java.io.*;import java.util.*; class GFG{     // function which find number    static int singleNumber(int[] nums, int n)    {        HashMap<Integer, Integer> m = new HashMap<>();        long sum1 = 0, sum2 = 0;        for (int i = 0; i < n; i++)        {            if (!m.containsKey(nums[i]))            {                sum1 += nums[i];                m.put(nums[i], 1);            }            sum2 += nums[i];        }         // applying the formula.        return (int)(2 * (sum1) - sum2);    }     // Driver code    public static void main(String args[])    {        int[] a = {2, 3, 5, 4, 5, 3, 4};        int n = 7;        System.out.println(singleNumber(a,n));         int[] b = {15, 18, 16, 18, 16, 15, 89};        System.out.println(singleNumber(b,n));    }} // This code is contributed by rachana soma
# Python3 program to find# element that appears once # function which find numberdef singleNumber(nums): # applying the formula.    return 2 * sum(set(nums)) - sum(nums) # driver codea = [2, 3, 5, 4, 5, 3, 4]print (int(singleNumber(a))) a = [15, 18, 16, 18, 16, 15, 89]print (int(singleNumber(a))) # This code is contributed by "Abhishek Sharma 44"
// C# program to find// element that appears onceusing System;using System.Collections.Generic; class GFG{     // function which find number    static int singleNumber(int[] nums, int n)    {        Dictionary<int,int> m = new Dictionary<int,int>();        long sum1 = 0, sum2 = 0;        for (int i = 0; i < n; i++)        {            if (!m.ContainsKey(nums[i]))            {                sum1 += nums[i];                m.Add(nums[i], 1);            }            sum2 += nums[i];        }         // applying the formula.        return (int)(2 * (sum1) - sum2);    }     // Driver code    public static void Main(String []args)    {        int[] a = {2, 3, 5, 4, 5, 3, 4};        int n = 7;        Console.WriteLine(singleNumber(a,n));         int[] b = {15, 18, 16, 18, 16, 15, 89};        Console.WriteLine(singleNumber(b,n));    }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to find// element that appears once         // function which find number    function singleNumber(nums,n)    {        let m = new Map();        let sum1 = 0, sum2 = 0;        for (let i = 0; i < n; i++)        {            if (!m.has(nums[i]))            {                sum1 += nums[i];                m.set(nums[i], 1);            }            sum2 += nums[i];        }          // applying the formula.        return (2 * (sum1) - sum2);    }         // Driver code    let a=[2, 3, 5, 4, 5, 3, 4];    let n = 7;    document.write(singleNumber(a,n)+"<br>");         let b=[15, 18, 16, 18, 16, 15, 89];    document.write(singleNumber(b,n));         // This code is contributed by unknown2108     </script>
Output:  
2
89
Another approach:
This is an efficient approach for finding the single element in a list of duplicate elements. In this approach, we are using binary search algorithm to find the single element in the list of duplicates elements.Before that, we need to make sure if the array is sorted. The first step is to sort the array because binary search algorithm wont work if the array is not sorted. 
Now let us move to the binary search implementation:
There are two halfs that are created by the only single element present in the array which are left half and right half. Now if there are duplicates present in the left half, then the 1st instance of the duplicate element in the left half is an even index and the 2nd instance is an odd index. The opposite of the left half happens in the right half(1st instance is odd index and the second instance is even index). Now apply binary search algorithm:
1)The solution is to take two indexes of the array(low and high) where low points to array-index 0 and high points to array-index (array size-2). We take out the mid index from the values by (low+high)/2.
2) Now check if the mid index value falls in the left half or the right half. If it falls in the left half then we change the low value to mid+1 and if it falls in the right half, then we change the high index to mid-1. To check it , we used a logic (if(arr[mid]==arr[mid^1]). If mid is an even number then mid^1 will be the next odd index , and if the condition gets satisfied, then we can say that we are in the left index,else we can say we are in the right half. But if mid is an odd index, then mid^1 takes us to mid-1 which is the previous even index , which is gets equal means we are in the right half else left half.
3) This is done because the aim of this implementation is to find the single element in the list of duplicates. It is only possible if low value is more than high value because at that moment low will be pointing to the index that contains the single element in the array.
4) After the loop ends, we return the value with low index.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int singleelement(int arr[], int n){    int low = 0, high = n - 2;    int mid;    while (low <= high) {        mid = (low + high) / 2;        if (arr[mid] == arr[mid ^ 1]) {            low = mid + 1;        }        else {            high = mid - 1;        }    }    return arr[low];}int main(){    int arr[] = { 2, 3, 5, 4, 5, 3, 4 };    int size = sizeof(arr) / sizeof(arr[0]);    sort(arr, arr + size);    cout << singleelement(arr, size);    return 0;} // This code is contributed by Sohom Das
import java.io.*;import java.util.Arrays; class GFG{     static int singleelement(int arr[], int n){    int low = 0, high = n - 2;    int mid;         while (low <= high)    {        mid = (low + high) / 2;        if (arr[mid] == arr[mid ^ 1])        {            low = mid + 1;        }        else        {            high = mid - 1;        }    }    return arr[low];} // Driver codepublic static void main(String[] args){    int arr[] = { 2, 3, 5, 4, 5, 3, 4 };    int size = 7;    Arrays.sort(arr);         System.out.println(singleelement(arr, size));}} // This code is contributed by dassohom5
def singleelement(arr, n):    low = 0    high = n - 2    mid = 0    while (low <= high):        mid = (low + high) // 2        if (arr[mid] == arr[mid ^ 1]):            low = mid + 1        else:            high = mid - 1         return arr[low]     # Driver codearr = [2, 3, 5, 4, 5, 3, 4]size = len(arr)arr.sort()print(singleelement(arr, size)) # This code is contributed by shivanisingh
using System;using System.Collections; class GFG{     static int singleelement(int[] arr, int n){    int low = 0, high = n - 2;    int mid;         while (low <= high)    {        mid = (low + high) / 2;                 if (arr[mid] == arr[mid ^ 1])        {            low = mid + 1;        }        else        {            high = mid - 1;        }    }    return arr[low];} // Driver codepublic static void Main(){    int[] arr = { 2, 3, 5, 4, 5, 3, 4 };    int size = 7;    Array.Sort(arr);         Console.WriteLine(singleelement(arr, size));}} // This code is contributed by dassohom5
<script> function singleelement(arr,n){    let low = 0, high = n - 2;    let mid;    while (low <= high) {        mid = (low + high) / 2;        if (arr[mid] == arr[mid ^ 1]) {            low = mid + 1;        }        else {            high = mid - 1;        }    }    return arr[low];}     let arr = [ 2, 3, 5, 4, 5, 3, 4 ];    let size = arr.length;    document.write(singleelement(arr, size));     </script>
Output:
2
The time complexity of the solution is O(N log(N))+O(log N) and its space complexity is O(1).
YouTubeGeeksforGeeks508K subscribersFind the element that appears once where every other element appears twice | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=5CRbjH0PmeE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
nitin mittal
vt_m
mohit kumar 29
rachana soma
princiraj1992
Akanksha_Rai
nidhi_biet
surbhityagi15
unknown2108
dassohom5
vaibhavrabadiya117
shivanisinghss2110
sweetyty
Bitwise-XOR
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
Subset Sum Problem | DP-25
Find Second largest element in an array
Merge two sorted arrays