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++
// 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; } |
Java
// 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 |
Python3
# 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 occurring once is", findSingle(ar, len(ar)) # This code is contributed by __Devesh Agrawal__ |
C#
// 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. |
PHP
<?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. ?> |
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++
// 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 |
Java
// 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 |
Python3
# 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" |
C#
// 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 */ |
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Find the element that appears once in a sorted array
- Find the element that appears once
- Find the only element that appears b times
- Reduce the array such that each element appears at most K times
- Reduce the array such that each element appears at most 2 times
- First element that appears even number of times in an array
- Maximum difference between two elements such that larger element appears after the smaller number
- Count all elements in the array which appears at least K times after their first occurrence
- Find Array formed by adding each element of given array with largest element in new array to its left
- Find last element after deleting every second element in array of n integers
- Find just strictly greater element from first array for each element in second array
- Largest element smaller than current element on left for every element in Array
- Maximum number of times str1 appears as a non-overlapping substring in str2
- Replace each element by the difference of the total size of the array and frequency of that element
- Check if minimum element in array is less than or equals half of every other element
- Range Query on array whose each element is XOR of index value and previous element
- Replace every array element by Bitwise Xor of previous and next element
- Maximum possible remainder when an element is divided by other element in the array
- Sum of (maximum element - minimum element) for all the subsets of an array.
- Form an array of distinct elements with each element as sum of an element from each array

