Given an array in which all numbers except two are repeated once. (i.e. we have 2n+2 numbers and n numbers are occurring twice and the remaining two have occurred once). Find those two numbers in the most efficient way.
Method 1(Use Sorting)
First, sort all the elements. In the sorted array, by comparing adjacent elements we can easily get the non-repeating elements.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > get2NonRepeatingNos( int nums[], int n)
{
sort(nums, nums + n);
vector< int > ans;
for ( int i = 0; i < n - 1; i = i + 2) {
if (nums[i] != nums[i + 1]) {
ans.push_back(nums[i]);
i = i - 1;
}
}
if (ans.size() == 1)
ans.push_back(nums[n - 1]);
return ans;
}
int main()
{
int arr[] = { 2, 3, 7, 9, 11, 2, 3, 11 };
int n = sizeof (arr) / sizeof (*arr);
vector< int > ans = get2NonRepeatingNos(arr, n);
cout << "The non-repeating elements are " << ans[0]
<< " and " << ans[1];
}
|
Java
import java.util.*;
public class Solution
{
static ArrayList<Integer> get2NonRepeatingNos( int nums[], int n)
{
Arrays.sort(nums);
ArrayList<Integer> ans = new ArrayList<>();
for ( int i = 0 ; i < n - 1 ; i = i + 2 ) {
if (nums[i] != nums[i + 1 ]) {
ans.add(nums[i]);
i = i - 1 ;
}
}
if (ans.size() == 1 )
ans.add(nums[n - 1 ]);
return ans;
}
public static void main(String[] args) {
int arr[] = { 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 };
int n = arr.length;
ArrayList<Integer> ans = get2NonRepeatingNos(arr, n);
System.out.print( "The non-repeating elements are " );
System.out.println(ans.get( 0 ) + " and " + ans.get( 1 ));
}
}
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
static ArrayList get2NonRepeatingNos( int [] nums, int n)
{
Array.Sort(nums);
ArrayList ans = new ArrayList();
for ( int i = 0; i < n - 1; i = i + 2) {
if (nums[i] != nums[i + 1]) {
ans.Add(nums[i]);
i = i - 1;
}
}
if (ans.Count == 1)
ans.Add(nums[n - 1]);
return ans;
}
static public void Main()
{
int [] arr = { 2, 3, 7, 9, 11, 2, 3, 11 };
int n = arr.Length;
ArrayList ans = get2NonRepeatingNos(arr, n);
Console.Write( "The non-repeating elements are " );
Console.WriteLine(ans[0] + " and " + ans[1]);
}
}
|
Javascript
function get2NonRepeatingNos(nums, n){
nums.sort();
var ans = [];
for (let i = 0; i < n - 1; i = i + 2) {
if (nums[i] != nums[i + 1]) {
ans.push(nums[i]);
i = i - 1;
}
}
if (ans.length == 1)
ans.push(nums[n - 1]);
return ans;
}
var arr = [ 2, 3, 7, 9, 11, 2, 3, 11 ];
var n = arr.length;
var ans = get2NonRepeatingNos(arr, n);
console.log( "The non-repeating elements are " + ans[0] + " and " + ans[1]);
|
Python3
def get2NonRepeatingNos(nums, n):
nums.sort();
ans = [];
i = 0 ;
while (i<n - 1 ):
if (nums[i] ! = nums[i + 1 ]):
ans.append(nums[i])
i = i + 1
else :
i = i + 2 ;
if ( len (arr) = = 1 ):
ans.append(nums[n - 1 ]);
return ans;
arr = [ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 ];
n = len (arr);
ans = get2NonRepeatingNos(arr, n);
print ( "The non-repeating elements are " , ans[ 0 ], " and " , ans[ 1 ]);
|
OutputThe non-repeating elements are 7 and 9
Time complexity: O(n log n)
Auxiliary Space: O(n)
Method 2(Use XOR)
Let x and y be the non-repeating elements we are looking for and arr[] be the input array. First, calculate the XOR of all the array elements.
xor = arr[0]^arr[1]^arr[2].....arr[n-1]
All the bits that are set in xor will be set in one non-repeating element (x or y) and not in others. So if we take any set bit of xor and divide the elements of the array in two sets – one set of elements with same bit set and another set with same bit not set. By doing so, we will get x in one set and y in another set. Now if we do XOR of all the elements in the first set, we will get the first non-repeating element, and by doing same in other sets we will get the second non-repeating element.
Let us see an example.
arr[] = {2, 4, 7, 9, 2, 4}
1) Get the XOR of all the elements.
xor = 2^4^7^9^2^4 = 14 (1110)
2) Get a number which has only one set bit of the xor.
Since we can easily get the rightmost set bit, let us use it.
set_bit_no = xor & ~(xor-1) = (1110) & ~(1101) = 0010
Now set_bit_no will have only set as rightmost set bit of xor.
3) Now divide the elements in two sets and do xor of
elements in each set and we get the non-repeating
elements 7 and 9. Please see the implementation for this step.
Approach :
Step 1: Xor all the elements of the array into a variable sum thus all the elements present twice in an array will get removed as for example, 4 = “100” and if 4 xor 4 => “100” xor “100” thus answer will be “000”.
Step 2: Thus in the sum the final answer will be 3 xor 5 as both 2 and 4 are xor with itself giving 0, therefore sum = “011” xor “101” i.e sum = “110” = 6.
Step 3: Now we will take 2’s Complement of sum i.e (-sum) = “010”.
Step 4: Now bitwise And the 2’s of sum with the sum i.e “110” & “010” gives the answer “010” (Aim for bitwise & is that we want to get a number that contains only the rightmost set bit of the sum).
Step 5: bitwise & all the elements of the array with this obtained sum, 2 = “010” & “010” = 2, 3 = “011” & “010” = “010” , 4 = “100” & “010” = “000”, 5 = “101” & “010” = “000”.
Step 6: As we can see that the bitwise & of 2,3 > 0 thus they will be xor with sum1 and bitwise & of 4,5 is resulting into 0 thus they will be xor with sum2.
Step 7: As 2 is present two times so getting xor with sum1 two times only the result 3 is being stored in it and As 4 is also present two times thus getting xor with sum2 will cancel it’s value and thus only 5 will remain there.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void get2NonRepeatingNos( int arr[], int n, int * x, int * y)
{
int Xor = arr[0];
int set_bit_no;
int i;
*x = 0;
*y = 0;
for (i = 1; i < n; i++)
Xor ^= arr[i];
set_bit_no = Xor & ~(Xor - 1);
for (i = 0; i < n; i++) {
if (arr[i] & set_bit_no)
*x = *x ^ arr[i];
else {
*y = *y ^ arr[i];
}
}
}
int main()
{
int arr[] = { 2, 3, 7, 9, 11, 2, 3, 11 };
int n = sizeof (arr) / sizeof (*arr);
int * x = new int [( sizeof ( int ))];
int * y = new int [( sizeof ( int ))];
get2NonRepeatingNos(arr, n, x, y);
cout << "The non-repeating elements are " << *x
<< " and " << *y;
}
|
C
#include <stdio.h>
#include <stdlib.h>
void get2NonRepeatingNos( int arr[], int n, int * x, int * y)
{
int Xor = arr[0];
int set_bit_no;
int i;
*x = 0;
*y = 0;
for (i = 1; i < n; i++)
Xor ^= arr[i];
set_bit_no = Xor & ~(Xor - 1);
for (i = 0; i < n; i++) {
if (arr[i] & set_bit_no)
*x = *x ^ arr[i];
else {
*y = *y ^ arr[i];
}
}
}
int main()
{
int arr[] = { 2, 3, 7, 9, 11, 2, 3, 11 };
int * x = ( int *) malloc ( sizeof ( int ));
int * y = ( int *) malloc ( sizeof ( int ));
get2NonRepeatingNos(arr, 8, x, y);
printf ( "The non-repeating elements are %d and %d" , *x,
*y);
getchar ();
}
|
Java
public class UniqueNumbers {
public static void UniqueNumbers2( int [] arr, int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
sum = (sum ^ arr[i]);
}
sum = (sum & -sum);
int sum1 = 0 ;
int sum2 = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
if ((arr[i] & sum) > 0 ) {
sum1 = (sum1 ^ arr[i]);
}
else {
sum2 = (sum2 ^ arr[i]);
}
}
System.out.println( "The non-repeating elements are "
+ sum1 + " and " + sum2);
}
public static void main(String[] args)
{
int [] arr = new int [] { 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 };
int n = arr.length;
UniqueNumbers2(arr, n);
}
}
|
Python3
def UniqueNumbers2(arr, n):
sums = 0
for i in range ( 0 , n):
sums = (sums ^ arr[i])
sums = (sums & - sums)
sum1 = 0
sum2 = 0
for i in range ( 0 , len (arr)):
if (arr[i] & sums) > 0 :
sum1 = (sum1 ^ arr[i])
else :
sum2 = (sum2 ^ arr[i])
print ( "The non-repeating elements are " ,
sum1, " and " , sum2)
if __name__ = = "__main__" :
arr = [ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 ]
n = len (arr)
UniqueNumbers2(arr, n)
|
C#
using System;
class GFG {
static void UniqueNumbers2( int [] arr, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum = (sum ^ arr[i]);
}
sum = (sum & -sum);
int sum1 = 0;
int sum2 = 0;
for ( int i = 0; i < arr.Length; i++) {
if ((arr[i] & sum) > 0) {
sum1 = (sum1 ^ arr[i]);
}
else {
sum2 = (sum2 ^ arr[i]);
}
}
Console.WriteLine( "The non-repeating "
+ "elements are " + sum1 + " and "
+ sum2);
}
static public void Main()
{
int [] arr = { 2, 3, 7, 9, 11, 2, 3, 11 };
int n = arr.Length;
UniqueNumbers2(arr, n);
}
}
|
Javascript
<script>
function UniqueNumbers2(arr, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
{
sum = (sum ^ arr[i]);
}
sum = (sum & -sum);
let sum1 = 0;
let sum2 = 0;
for (let i = 0; i < arr.length; i++)
{
if ((arr[i] & sum) > 0)
{
sum1 = (sum1 ^ arr[i]);
}
else
{
sum2 = (sum2 ^ arr[i]);
}
}
document.write( "The non-repeating " +
"elements are " + sum1 +
" and " + sum2);
}
let arr = [ 2, 3, 7, 9, 11, 2, 3, 11 ];
let n = arr.length;
UniqueNumbers2(arr, n);
</script>
|
OutputThe non-repeating elements are 7 and 9
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer below post for detailed explanation :
Find the two numbers with odd occurrences in an unsorted array
Method 3(Use Maps)
In this method, we simply count frequency of each element. The elements whose frequency is equal to 1 is the number which is non-repeating. The solution is explained below in the code-
C++
#include <bits/stdc++.h>
using namespace std;
void get2NonRepeatingNos( int arr[], int n)
{
map< int , int > m;
for ( int i = 0; i < n; i++) {
m[arr[i]]++;
}
cout << "The non-repeating elements are " ;
for ( auto & x : m) {
if (x.second == 1) {
cout << x.first << " " ;
}
}
}
int main()
{
int arr[] = { 2, 3, 7, 9, 11, 2, 3, 11 };
int n = sizeof (arr) / sizeof (arr[0]);
get2NonRepeatingNos(arr, n);
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
public static void print2SingleNumbers( int [] nums){
TreeMap<Integer, Integer> map = new TreeMap<>();
int n = nums.length;
for ( int i = 0 ; i<n; i++){
if (map.containsKey(nums[i]))
map.remove(nums[i]);
else
map.put(nums[i], 1 );
}
System.out.println( "The non-repeating integers are " + map.firstKey() + " " + map.lastKey());
}
public static void main (String[] args) {
int [] nums = new int []{ 2 , 11 , 3 , 11 , 7 , 3 , 9 , 2 };
print2SingleNumbers(nums);
}
}
|
Python3
def get2NonRepeatingNos(arr, n):
m = {}
for i in range (n):
if (arr[i] not in m):
m[arr[i]] = 0
m[arr[i]] = m[arr[i]] + 1
print ( "The non-repeating elements are" , end = " " )
for key,value in m.items():
if (value = = 1 ):
print (key,end = " " )
arr = [ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 ]
n = len (arr)
get2NonRepeatingNos(arr, n)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
public static void print2SingleNumbers( int [] A)
{
Dictionary< int , int > map = new Dictionary< int , int >();
int n = A.Length;
for ( int i = 0 ; i < n; i++)
{
if (map.ContainsKey(A[i]))
map.Remove(A[i]);
else
map.Add(A[i], 1);
}
Console.Write( "The non-repeating integers are " );
foreach (KeyValuePair< int , int > it in map){
if (it.Value == 1) {
Console.Write(it.Key + " " );
}
}
}
public static void Main(String[] args) {
int [] nums = new int []{2, 11, 3, 11, 7, 3, 9, 2};
print2SingleNumbers(nums);
}
}
|
Javascript
<script>
function get2NonRepeatingNos(arr, n)
{
let m = new Map();
for (let i = 0; i < n; i++) {
if (!m.has(arr[i]))
{
m.set(arr[i],0);
}
m.set(arr[i],m.get(arr[i])+1);
}
document.write( "The non-repeating elements are " );
for (let [key,value] of m) {
if (value == 1) {
document.write(key, " " );
}
}
}
let arr = [ 2, 3, 7, 9, 11, 2, 3, 11 ];
let n = arr.length;
get2NonRepeatingNos(arr, n);
</script>
|
OutputThe non-repeating elements are 7 9
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Method 4(Use Sets):
In this method, We check if the element already exists, if it exists we remove it else we add it to the set.
Approach:
Step 1: Take each element and check if it exists in the set or not. If it exists go to step 3. If it doesn’t exist go to step 2.
Step 2: Add the element to the set and go to step 4.
Step 3: Remove the element from the set and go to step 4.
Step 4: Print the elements of the set.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void print2SingleNumbers( int nums[], int n)
{
multiset< int > set;
for ( int i = 0; i < n; i++) {
auto it = set.find(nums[i]);
if (it != set.end())
set.erase(it);
else
set.insert(nums[i]);
}
cout << "The 2 non repeating numbers are : "
<< *set.begin() << " " << *next(set.begin(), 1);
}
int main()
{
int nums[] = { 2, 3, 7, 9, 11, 2, 3, 11 };
int n = sizeof (nums) / sizeof (nums[0]);
print2SingleNumbers(nums, n);
}
|
Java
import java.util.LinkedHashSet;
import java.util.Iterator;
import java.io.*;
class GFG {
public static void print2SingleNumbers( int [] nums){
LinkedHashSet<Integer> set = new LinkedHashSet<>();
int n = nums.length;
for ( int i = 0 ; i<n; i++){
if (set.contains(nums[i]))
set.remove(nums[i]);
else
set.add(nums[i]);
}
Iterator<Integer> i = set.iterator();
System.out.println( "The 2 non repeating numbers are : " + i.next() + " " + i.next());
}
public static void main (String[] args) {
int [] nums = new int []{ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 };
print2SingleNumbers(nums);
}
}
|
Python3
def print2SingleNumbers(nums):
set_ = set ()
n = len (nums)
for i in nums:
if i in set_:
set_.remove(i)
else :
set_.add(i)
print ( "The 2 non repeating numbers are : " + " " .join( map ( str , set_)))
nums = [ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 ]
print2SingleNumbers(nums)
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static void print2SingleNumbers( int [] nums)
{
HashSet< int > set = new HashSet< int >();
int n = nums.Length;
for ( int i = 0; i < n; i++) {
if ( set .Contains(nums[i]))
set .Remove(nums[i]);
else
set .Add(nums[i]);
}
Console.Write( "The 2 non repeating numbers are : " );
foreach ( var val in set ) Console.Write(val + " " );
}
public static void Main( string [] args)
{
int [] nums = new int [] { 2, 3, 7, 9, 11, 2, 3, 11 };
print2SingleNumbers(nums);
}
}
|
Javascript
function print2SingleNumbers(nums)
{
let set = new Set();
let n = nums.length;
for ( var i of nums)
{
if (set.has(i))
set. delete (i);
else
set.add(i);
}
console.log( "The 2 non repeating numbers are :" , [...set].join( ' ' ));
}
let nums = [2, 3, 7, 9, 11, 2, 3, 11];
print2SingleNumbers(nums);
|
OutputThe 2 non repeating numbers are : 7 9
Time Complexity: O(n) for a given array of size n
Auxiliary Space: O(n)
C++
#include <bits/stdc++.h>
using namespace std;
void get2NonRepeatingNos( int arr[], int n)
{
set< int > s;
for ( int i = 0; i < n; i++)
{
if (s.find(arr[i]) != s.end())
s.erase(arr[i]);
else
s.insert(arr[i]);
}
cout << "The 2 non repeating numbers are : " ;
for ( auto it : s)
cout << it << " " ;
cout << endl;
}
int main()
{
int arr[] = {2, 3, 7, 9, 11, 2, 3, 11};
int n = sizeof (arr) / sizeof (arr[0]);
get2NonRepeatingNos(arr, n);
}
|
Java
import java.util.*;
class GFG {
static void get2NonRepeatingNos( int arr[], int n)
{
HashSet<Integer> s = new HashSet<Integer>();
for ( int i = 0 ; i < n; i++)
{
if (s.contains(arr[i]))
s.remove(arr[i]);
else
s.add(arr[i]);
}
System.out.print( "The 2 non repeating numbers are : " );
for ( int it : s)
System.out.print(it + " " );
System.out.println();
}
public static void main (String[] args) {
int arr[] = { 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 };
int n = arr.length;
get2NonRepeatingNos(arr, n);
}
}
|
Python3
def get2NonRepeatingNos(arr, n):
s = set ()
for i in range (n):
if (arr[i] in s):
s.remove(arr[i])
else :
s.add(arr[i])
print ( "The 2 non repeating numbers are :" ,end = " " )
for it in s:
print (it,end = " " )
print ()
arr = [ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 ]
n = len (arr)
get2NonRepeatingNos(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void get2NonRepeatingNos( int [] arr, int n)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n; i++)
{
if (s.Contains(arr[i]))
s.Remove(arr[i]);
else
s.Add(arr[i]);
}
Console.Write( "The 2 non repeating numbers are : " );
foreach ( int it in s)
Console.Write(it + " " );
Console.WriteLine();
}
public static void Main(String[] args)
{
int [] arr = {2, 3, 7, 9, 11, 2, 3, 11};
int n = arr.Length;
get2NonRepeatingNos(arr, n);
}
}
|
Javascript
<script>
function get2NonRepeatingNos(arr, n)
{
let s = new Set();
for (let i = 0; i < n; i++)
{
if (s.has(arr[i]))
s. delete (arr[i]);
else
s.add(arr[i]);
}
document.write( "The 2 non repeating numbers are : " );
for (const it of s)
document.write(it, " " );
document.write( "</br>" );
}
let arr = [2, 3, 7, 9, 11, 2, 3, 11];
let n = arr.length;
get2NonRepeatingNos(arr, n);
</script>
|
OutputThe 2 non repeating numbers are : 7 9
Time Complexity: O(n log n)
Auxiliary Space: O(n)