Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3
Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and the inner loop counts the number of occurrences of the element picked by the outer loop. The time complexity of this solution is O(n2).
Below is the implementation of the brute force approach :
C++
#include<bits/stdc++.h>
using namespace std;
int getOddOccurrence( int arr[], int arr_size)
{
for ( int i = 0; i < arr_size; i++) {
int count = 0;
for ( int j = 0; j < arr_size; j++)
{
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << getOddOccurrence(arr, n);
return 0;
}
|
Java
class OddOccurrence {
static int getOddOccurrence( int arr[], int arr_size)
{
int i;
for (i = 0 ; i < arr_size; i++) {
int count = 0 ;
for ( int j = 0 ; j < arr_size; j++) {
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0 )
return arr[i];
}
return - 1 ;
}
public static void main(String[] args)
{
int arr[] = new int []{ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 };
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
|
Python3
def getOddOccurrence(arr, arr_size):
for i in range ( 0 ,arr_size):
count = 0
for j in range ( 0 , arr_size):
if arr[i] = = arr[j]:
count + = 1
if (count % 2 ! = 0 ):
return arr[i]
return - 1
arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ]
n = len (arr)
print (getOddOccurrence(arr, n))
|
C#
using System;
class GFG
{
static int getOddOccurrence( int []arr, int arr_size)
{
for ( int i = 0; i < arr_size; i++) {
int count = 0;
for ( int j = 0; j < arr_size; j++) {
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
public static void Main()
{
int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.Write(getOddOccurrence(arr, n));
}
}
|
PHP
<?php
function getOddOccurrence(& $arr , $arr_size )
{
$count = 0;
for ( $i = 0;
$i < $arr_size ; $i ++)
{
for ( $j = 0;
$j < $arr_size ; $j ++)
{
if ( $arr [ $i ] == $arr [ $j ])
$count ++;
}
if ( $count % 2 != 0)
return $arr [ $i ];
}
return -1;
}
$arr = array (2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2);
$n = sizeof( $arr );
echo (getOddOccurrence( $arr , $n ));
?>
|
Javascript
<script>
function getOddOccurrence(arr, arr_size)
{
for (let i = 0; i < arr_size; i++) {
let count = 0;
for (let j = 0; j < arr_size; j++)
{
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
let arr = [ 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 ];
let n = arr.length;
document.write(getOddOccurrence(arr, n));
</script>
|
Output :
5
Time Complexity: O(n^2)
Auxiliary Space: O(1)
A Better Solution is to use Hashing. Use array elements as a key and their counts as values. Create an empty hash table. One by one traverse the given array elements and store counts. The time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
C++
#include <bits/stdc++.h>
using namespace std;
int getOddOccurrence( int arr[], int size)
{
unordered_map< int , int > hash;
for ( int i = 0; i < size; i++)
{
hash[arr[i]]++;
}
for ( auto i : hash)
{
if (i.second % 2 != 0)
{
return i.first;
}
}
return -1;
}
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 2, 4,
3, 5, 2, 4, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << getOddOccurrence(arr, n);
return 0;
}
|
Java
import java.io.*;
import java.util.HashMap;
class OddOccurrence
{
static int getOddOccurrence( int arr[], int n)
{
HashMap<Integer,Integer> hmap = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
if (hmap.containsKey(arr[i]))
{
int val = hmap.get(arr[i]);
hmap.put(arr[i], val + 1 );
}
else
hmap.put(arr[i], 1 );
}
for (Integer a:hmap.keySet())
{
if (hmap.get(a) % 2 != 0 )
return a;
}
return - 1 ;
}
public static void main(String[] args)
{
int arr[] = new int []{ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 };
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
|
Python3
def getOddOccurrence(arr,size):
Hash = dict ()
for i in range (size):
Hash [arr[i]] = Hash .get(arr[i], 0 ) + 1 ;
for i in Hash :
if ( Hash [i] % 2 ! = 0 ):
return i
return - 1
arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ]
n = len (arr)
print (getOddOccurrence(arr, n))
|
C#
using System;
using System.Collections.Generic;
public class OddOccurrence
{
static int getOddOccurrence( int []arr, int n)
{
Dictionary< int , int > hmap = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
if (hmap.ContainsKey(arr[i]))
{
int val = hmap[arr[i]];
hmap.Remove(arr[i]);
hmap.Add(arr[i], val + 1);
}
else
hmap.Add(arr[i], 1);
}
foreach (KeyValuePair< int , int > entry in hmap)
{
if (entry.Value % 2 != 0)
{
return entry.Key;
}
}
return -1;
}
public static void Main(String[] args)
{
int []arr = new int []{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int n = arr.Length;
Console.WriteLine(getOddOccurrence(arr, n));
}
}
|
Javascript
<script>
function getOddOccurrence(arr,n)
{
let hmap = new Map();
for (let i = 0; i < n; i++)
{
if (hmap.has(arr[i]))
{
let val = hmap.get(arr[i]);
hmap.set(arr[i], val + 1);
}
else
{
hmap.set(arr[i], 1);
}
}
for (let [key, value] of hmap.entries())
{
if (hmap.get(key) % 2 != 0)
return key;
}
return -1;
}
let arr=[2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2];
let n = arr.length;
document.write(getOddOccurrence(arr, n));
</script>
|
Output :
5
Time Complexity: O(n)
Auxiliary Space: O(n)
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring elements.
Here ^ is the XOR operators;
Note :
x^0 = x
x^y=y^x (Commutative property holds)
(x^y)^z = x^(y^z) (Distributive property holds)
x^x=0
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int getOddOccurrence( int ar[], int ar_size)
{
int res = 0;
for ( int i = 0; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
int main()
{
int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int n = sizeof (ar)/ sizeof (ar[0]);
cout << getOddOccurrence(ar, n);
return 0;
}
|
C
#include <stdio.h>
int getOddOccurrence( int ar[], int ar_size)
{
int res = 0;
for ( int i = 0; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
int main()
{
int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int n = sizeof (ar) / sizeof (ar[0]);
printf ( "%d" , getOddOccurrence(ar, n));
return 0;
}
|
Java
class OddOccurrence
{
int getOddOccurrence( int ar[], int ar_size)
{
int i;
int res = 0 ;
for (i = 0 ; i < ar_size; i++)
{
res = res ^ ar[i];
}
return res;
}
public static void main(String[] args)
{
OddOccurrence occur = new OddOccurrence();
int ar[] = new int []{ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 };
int n = ar.length;
System.out.println(occur.getOddOccurrence(ar, n));
}
}
|
Python3
def getOddOccurrence(arr):
res = 0
for element in arr:
res = res ^ element
return res
arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ]
print ( "%d" % getOddOccurrence(arr))
|
C#
using System;
class GFG
{
static int getOddOccurrence( int []arr, int arr_size)
{
int res = 0;
for ( int i = 0; i < arr_size; i++)
{
res = res ^ arr[i];
}
return res;
}
public static void Main()
{
int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.Write(getOddOccurrence(arr, n));
}
}
|
PHP
<?php
function getOddOccurrence(& $ar , $ar_size )
{
$res = 0;
for ( $i = 0; $i < $ar_size ; $i ++)
$res = $res ^ $ar [ $i ];
return $res ;
}
$ar = array (2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2);
$n = sizeof( $ar );
echo (getOddOccurrence( $ar , $n ));
?>
|
Javascript
<script>
function getOddOccurrence( ar, ar_size)
{
let res = 0;
for (let i = 0; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
let arr = [ 2, 3, 5, 4, 5, 2, 4,
3, 5, 2, 4, 4, 2 ];
let n = arr.length;
document.write(getOddOccurrence(arr, n));
</script>
|
Output :
5
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3:Using Built-in Python functions:
- Count the frequencies of every element using the Counter function
- Traverse in frequency dictionary
- Check which element has an odd frequency.
- Print that element and break the loop
Below is the implementation:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int oddElement( int arr[], int n) {
unordered_map< int , int > count_map;
for ( int i = 0; i < n; i++) {
count_map[arr[i]]++;
}
for ( int i = 0; i < n; i++) {
if (count_map[arr[i]] % 2 != 0) {
return arr[i];
}
}
}
int main() {
int arr[] = {1, 1, 3, 3, 5, 6, 6};
int n = sizeof (arr) / sizeof (arr[0]);
cout << oddElement(arr, n);
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static void main(String[] args) {
int [] arr = new int []{ 1 , 1 , 3 , 3 , 5 , 6 , 6 };
Map<Integer, Integer> countMap = new HashMap<>();
for ( int i = 0 ; i < arr.length; i++) {
if (countMap.containsKey(arr[i])) {
countMap.put(arr[i], countMap.get(arr[i]) + 1 );
} else {
countMap.put(arr[i], 1 );
}
}
for ( int i = 0 ; i < arr.length; i++) {
if (countMap.get(arr[i]) % 2 != 0 ) {
System.out.println(arr[i]);
return ;
}
}
}
}
|
Python3
from collections import Counter
def oddElement(arr, n):
count_map = Counter(arr)
for i in range ( 0 , n):
if (count_map[arr[i]] % 2 ! = 0 ):
return arr[i]
if __name__ = = "__main__" :
arr = [ 1 , 1 , 3 , 3 , 5 , 6 , 6 ]
n = len (arr)
print (oddElement(arr, n))
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static int oddElement( int [] arr, int n) {
Dictionary< int , int > count_map= new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (count_map.ContainsKey(arr[i]))
{
var val = count_map[arr[i]];
count_map.Remove(arr[i]);
count_map.Add(arr[i], val + 1);
}
else
{
count_map.Add(arr[i], 1);
}
}
for ( int i = 0; i < n; i++)
{
if (count_map[arr[i]] % 2 != 0) {
return arr[i];
}
}
return -1;
}
static public void Main()
{
int [] arr = {1, 1, 3, 3, 5, 6, 6};
int n = arr.Length;
Console.Write(oddElement(arr, n));
}
}
|
Javascript
const countMap = new Map();
function oddElement(arr) {
for (let i = 0; i < arr.length; i++) {
if (countMap.has(arr[i])) {
countMap.set(arr[i], countMap.get(arr[i]) + 1);
} else {
countMap.set(arr[i], 1);
}
}
for (let i = 0; i < arr.length; i++) {
if (countMap.get(arr[i]) % 2 != 0) {
return arr[i];
}
}
}
const arr = [1, 1, 3, 3, 5, 6, 6];
console.log(oddElement(arr));
|
Output:
5
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 4:Using HashSet
This problem can also be solved using HashSet by traversing the array and inserting element if not already present else deleting the element from the HashSet. So, after the traversal is complete the only element left in the HashSet is the element which is present three times.
C++
#include<bits/stdc++.h>
using namespace std;
int getOddOccurrence( int arr[], int N)
{
unordered_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]);
}
}
return *(s.begin());
}
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << getOddOccurrence(arr, n);
return 0;
};
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int getOddOccurrence( int arr[], int N)
{
HashSet<Integer> s = new HashSet<>();
for ( int i = 0 ; i < N; i++) {
if (s.contains(arr[i])) {
s.remove(arr[i]);
}
else {
s.add(arr[i]);
}
}
int ans = 0 ;
for ( int val : s) {
ans = val;
break ;
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 };
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
|
Python3
def getOddOccurrence(arr, N):
s = set ()
for i in range (N):
if arr[i] in s:
s.remove(arr[i]);
else :
s.add(arr[i]);
return s
arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ];
n = len (arr);
print ( * getOddOccurrence(arr, n));
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static int getOddOccurrence( 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]);
}
}
int ans = 0;
foreach ( int val in s) {
ans = val;
break ;
}
return ans;
}
public static void Main( string [] args)
{
int [] arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.WriteLine(getOddOccurrence(arr, n));
}
}
|
Javascript
function getOddOccurrence(arr, N)
{
let s = new Set();
for ( var i=0; i<N; i++){
if (s.has(arr[i])){
s. delete (arr[i]);
} else {
s.add(arr[i]);
}
}
return Array.from(s).pop();
}
let arr = [ 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 ];
let n = arr.length;
console.log(getOddOccurrence(arr, n));
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 5 (Using binary search) :First sort the array for binary search function . Then we can find frequency of all array elements using lower_bound and upper bound . If frequency is odd then print that element .
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getOddOccurrence( int arr[], int n)
{
int count = 0 , ans = -1;
sort(arr,arr+n);
for ( int i = 0 ; i < n ;i++)
{
int first_index = lower_bound(arr,arr+n,arr[i])- arr;
int last_index = upper_bound(arr,arr+n,arr[i])- arr-1;
i = last_index;
int fre = last_index-first_index+1;
if (fre % 2 != 0)
{
ans = arr[i];
}
}
return ans;
}
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << getOddOccurrence(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
static int getOddOccurrence( int arr[], int n)
{
int count = 0 , ans = - 1 ;
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++) {
int firstIndex
= Arrays.binarySearch(arr, arr[i]);
int lastIndex
= firstIndex
+ (arr.length - 1 - arr[firstIndex]);
i = lastIndex;
int fre = lastIndex - firstIndex
+ 1 ;
if (fre % 2 != 0 ) {
ans = arr[i];
}
}
return ans;
}
public static void main(String[] args)
{
int arr[]
= { 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 };
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
|
Python3
from bisect import bisect_left, bisect_right
def getOddOccurrence(arr, n):
ans = - 1
arr.sort()
i = 0
while i < n:
first_index = bisect_left(arr, arr[i])
last_index = bisect_right(arr, arr[i])
i = last_index
fre = last_index - first_index + 1
if fre % 2 ! = 0 :
ans = arr[i]
return ans
arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ]
n = len (arr)
print (getOddOccurrence(arr, n))
|
Javascript
function getOddOccurrence(arr) {
let count = 0, ans = -1;
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
let firstIndex = arr.indexOf(arr[i]);
let lastIndex = arr.lastIndexOf(arr[i]);
i = lastIndex;
let fre = lastIndex - firstIndex + 1;
if (fre % 2 != 0) {
ans = arr[i];
}
}
return ans;
}
let arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2];
console.log(getOddOccurrence(arr));
|
C#
using System;
using System.Linq;
public class MainClass
{
static int GetOddOccurrence( int [] arr, int n)
{
int count = 0, ans = -1;
Array.Sort(arr);
for ( int i = 0; i < n; i++)
{
int firstIndex
= Array.BinarySearch(arr, arr[i]);
int lastIndex
= firstIndex
+ (arr.Length - 1 - arr[firstIndex]);
i = lastIndex;
int fre = lastIndex - firstIndex
+ 1;
if (fre % 2 != 0)
{
ans = arr[i];
}
}
return ans;
}
public static void Main( string [] args)
{
int [] arr
= { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.WriteLine(GetOddOccurrence(arr, n));
}
}
|
Time Complexity: O(N*Log2N)
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.