Find single in an array of 2n+1 integer elements
Given an array with 2n+1 integers, n elements appear twice in arbitrary places in the array and a single integer appears only once somewhere inside. Find the lonely integer with O(n) operations and O(1) extra memory.
Examples :
Input : { 1, 1, 2, 2, 3, 3, 4, 4, 5}
Output : 5
Input : { 7, 9, 6, 8, 3, 7, 8, 6, 9}
Output : 3
The idea is to do XOR of all elements. XOR of all elements gives us the result. The idea is based on below XOR properties.
- XOR of a number with itself is 0.
- XOR of a number with 0 is the number.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int findNonRepeating( int arr[],
int n)
{
int res = 0;
for ( int i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
int main()
{
int arr[] = { 3, 8, 3, 2, 2, 1, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findNonRepeating(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int findNonRepeating( int []arr,
int n)
{
int res = 0 ;
for ( int i = 0 ; i < n; i++)
res = res ^ arr[i];
return res;
}
static public void main (String[] args)
{
int []arr = { 3 , 8 , 3 , 2 , 2 , 1 , 1 };
int n = arr.length;
System.out.println(findNonRepeating(arr, n));
}
}
|
Python
def findNonRepeating(a, n):
res = 0
for i in range (n):
res ^ = a[i]
return res
a = [ 3 , 8 , 3 , 2 , 2 , 1 , 1 ]
n = len (a)
print findNonRepeating(a, n)
|
C#
using System;
class GFG
{
static int findNonRepeating( int []arr,
int n)
{
int res = 0;
for ( int i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
static public void Main (String []args)
{
int []arr = {3, 8, 3, 2, 2, 1, 1};
int n = arr.Length;
Console.WriteLine(findNonRepeating(arr,
n));
}
}
|
PHP
<?php
function findNonRepeating( $arr , $n )
{
$res = 0;
for ( $i = 0; $i < $n ; $i ++)
$res = $res ^ $arr [ $i ];
return $res ;
}
$arr = array ( 3, 8, 3, 2, 2, 1, 1 );
$n = sizeof( $arr );
echo (findNonRepeating( $arr , $n ));
?>
|
Javascript
<script>
function findNonRepeating(arr, n)
{
let res = 0;
for (let i = 0; i < n; i++)
res = res ^ arr[i];
return res;
}
let arr = [ 3, 8, 3, 2, 2, 1, 1 ];
let n = arr.length;
document.write(findNonRepeating(arr, n));
</script>
|
Time Complexity: O(n).
Space Complexity: O(1).
Last Updated :
20 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...