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

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 an element with 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 count of occurrences is used as value in hash table.
2) Traverse the array again and print the element with count 1 in 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 single occurrence. The idea is based on 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 code
int 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;
    }

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the array 
// element that appears only once
class 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to find the once 
# appearing element in array
def 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 code
ar = [2, 3, 5, 4, 5, 3, 4]
print "Element occuring once is", findSingle(ar, len(ar))
  
# This code is contributed by __Devesh Agrawal__

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the array 
// element that appears only once
using 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right



Output:

Element occurring once is 2

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 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find 
// element that appears once
#include <bits/stdc++.h>
  
using namespace std;
  
// function which find number
int 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 code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find 
// element that appears once
import 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find 
# element that appears once
  
# function which find number
def singleNumber(nums):
  
# applying the formula.
    return 2 * sum(set(nums)) - sum(nums)
  
# driver code
a = [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"

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find 
// element that appears once
using 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 */

chevron_right



Output:

2
89

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



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


8


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.