Two odd occurring elements in an array where all other occur even times
Last Updated :
27 Mar, 2023
Given an array where all elements appear even number of times except two, print the two odd occurring elements. It may be assumed that the size of array is at-least two.
Examples:
Input : arr[] = {2, 3, 8, 4, 4, 3, 7, 8}
Output : 2 7
Input : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50}
Output : 7 15
Simple solution :
Approach :
A simple solution is to use two nested loops. The outer loop traverses through all elements. The inner loop counts occurrences of the current element. We print the elements whose counts of occurrences are odd.
Below is the code of the given approach :
C++
#include <bits/stdc++.h>
using namespace std;
void printOdds( int arr[], int n)
{
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count += 1;
}
}
if (count % 2 != 0) {
cout << arr[i]
<< " " ;
}
}
cout << endl;
}
int main()
{
int arr[] = { 2, 3, 3, 4, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
printOdds(arr, n);
return 0;
}
|
C
#include <stdio.h>
void printOdds( int arr[], int n)
{
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count += 1;
}
}
if (count % 2 != 0) {
printf (
"%d " ,
arr[i]);
}
}
printf ( "\n" );
}
int main()
{
int arr[] = { 2, 3, 3, 4, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
printOdds(arr, n);
return 0;
}
|
Java
public class GFG {
static void printOdds( int [] arr, int n)
{
for ( int i = 0 ; i < n; i++) {
int count = 0 ;
for ( int j = 0 ; j < n; j++) {
if (arr[i] == arr[j]) {
count += 1 ;
}
}
if (count % 2 != 0 ) {
System.out.print(arr[i]+ " " );
}
}
System.out.print( "\n" );
}
public static void main (String[] args)
{
int arr[] = { 2 , 3 , 3 , 4 , 4 , 5 };
int n = arr.length;
printOdds(arr, n);
}
}
|
Python3
def printOdds(arr, n) :
for i in range ( 0 ,n) :
count = 0
for j in range ( 0 ,n) :
if arr[i] = = arr[j] :
count + = 1
if count % 2 ! = 0 :
print (arr[i],end = ' ' )
if __name__ = = "__main__" :
arr = [ 2 , 3 , 3 , 4 , 4 , 5 ]
n = len (arr)
printOdds(arr,n)
|
C#
using System;
public class GFG
{
public static void printOdds( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
{
var count = 0;
for ( int j = 0; j < n; j++)
{
if (arr[i] == arr[j])
{
count += 1;
}
}
if (count % 2 != 0)
{
Console.Write(arr[i].ToString() + " " );
}
}
Console.Write( "\n" );
}
public static void Main(String[] args)
{
int [] arr = {2, 3, 3, 4, 4, 5};
var n = arr.Length;
GFG.printOdds(arr, n);
}
}
|
Javascript
function printOdds(arr, n)
{
for ( var i = 0; i < n; i++) {
let count = 0;
for ( var j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count += 1;
}
}
if (count % 2 != 0) {
process.stdout.write(arr[i] + " " );
}
}
process.stdout.write( "\n" );
}
let arr = [ 2, 3, 3, 4, 4, 5 ];
let n = arr.length;
printOdds(arr, n);
|
Complexity Analysis:
- Time complexity : O(n^2)
- Auxiliary space : O(n)
A better solution is to use hashing. Time complexity of this solution is O(n) but it requires extra space.
We can construct a frequency hashmap, then iterate over all of its key – value pairs, and print all keys whose values (frequency) are odd.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printOdds( int arr[], int n)
{
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++)
freq[arr[i]]++;
for ( auto & it: freq) {
if (it.second % 2)
cout << it.first << " " ;
}
}
int main()
{
int arr[] = { 2, 3, 3, 4, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
printOdds(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void printOdds( int arr[], int n)
{
TreeMap<Integer, Integer> freq = new TreeMap<>(Collections.reverseOrder());
for ( int i = 0 ; i < n; i++) {
freq.put(arr[i],
freq.getOrDefault(arr[i], 0 ) + 1 );
}
for ( int i : freq.keySet()) {
if (freq.get(i) % 2 == 1 )
System.out.print(i + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 3 , 4 , 4 , 5 };
int n = arr.length;
printOdds(arr, n);
}
}
|
Python3
from collections import defaultdict
def printOdds(arr, n):
freq = defaultdict( int )
for i in range (n):
freq[arr[i]] + = 1
for key, value in freq.items():
if value % 2 :
print (key,end = " " )
arr = [ 2 , 3 , 3 , 4 , 4 , 5 ]
n = len (arr)
printOdds(arr, n)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static void printOdds( int [] arr, int n)
{
Dictionary< int , int > freq
= new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (freq.ContainsKey(arr[i])) {
int val = freq[arr[i]];
freq.Remove(arr[i]);
freq.Add(arr[i], val + 1);
}
else {
freq.Add(arr[i], 1);
}
}
foreach (KeyValuePair< int , int > entry in freq)
{
if (entry.Value % 2 != 0)
Console.Write(entry.Key + " " );
}
}
static public void Main()
{
int [] arr = { 2, 3, 3, 4, 4, 5 };
int n = 6;
printOdds(arr, n);
}
}
|
Javascript
function printOdds(arr, n)
{
var mp = new Map();
for ( var i = 0; i < n; i++)
{
if (mp.has(arr[i]))
mp.set(arr[i], mp.get(arr[i])+1);
else
mp.set(arr[i], 1);
}
let el=[];
mp.forEach(( key,value) => {
if (key%2!=0)
{
el.push(value);
}
});
console.log(el);
}
let arr = [2, 3, 3, 4, 4, 5 ];
let n = arr.length;
printOdds(arr, n);
|
Complexity Analysis:
- Time Complexity: O(n)
- Space Complexity: O(n)
An efficient solution is to use bitwise operators. The idea is based on approach used in two missing elements and two repeating elements.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printOdds( int arr[], int n)
{
int res = 0;
for ( int i = 0; i < n; i++)
res = res ^ arr[i];
int set_bit = res & (~(res - 1));
int x = 0, y = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] & set_bit)
x = x ^ arr[i];
else
y = y ^ arr[i];
}
cout << x << " " << y;
}
int main()
{
int arr[] = { 2, 3, 3, 4, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
printOdds(arr, n);
return 0;
}
|
Java
class GFG
{
static void printOdds( int arr[],
int n)
{
int res = 0 ;
for ( int i = 0 ; i < n; i++)
res = res ^ arr[i];
int set_bit = res &
(~(res - 1 ));
int x = 0 , y = 0 ;
for ( int i = 0 ; i < n; i++)
{
if ((arr[i] & set_bit) != 0 )
x = x ^ arr[i];
else
y = y ^ arr[i];
}
System.out.println( x + " " + y);
}
public static void main(String [] args)
{
int arr[] = { 2 , 3 , 3 ,
4 , 4 , 5 };
int n = arr.length;
printOdds(arr, n);
}
}
|
Python3
def printOdds(arr, n):
res = 0
for i in range ( 0 , n):
res = res ^ arr[i]
set_bit = res & (~(res - 1 ))
x = 0
y = 0
for i in range ( 0 , n):
if (arr[i] & set_bit):
x = x ^ arr[i]
else :
y = y ^ arr[i]
print (x , y, end = "")
arr = [ 2 , 3 , 3 , 4 , 4 , 5 ]
n = len (arr)
printOdds(arr, n)
|
C#
using System;
class GFG
{
static void printOdds( int []arr,
int n)
{
int res = 0;
for ( int i = 0; i < n; i++)
res = res ^ arr[i];
int set_bit = res &
(~(res - 1));
int x = 0, y = 0;
for ( int i = 0; i < n; i++)
{
if ((arr[i] & set_bit) != 0)
x = x ^ arr[i];
else
y = y ^ arr[i];
}
Console.WriteLine(x + " " + y);
}
public static void Main()
{
int []arr = { 2, 3, 3,
4, 4, 5 };
int n = arr.Length;
printOdds(arr, n);
}
}
|
PHP
<?php
function printOdds( $arr , $n )
{
$res = 0;
for ( $i = 0; $i < $n ; $i ++)
$res = $res ^ $arr [ $i ];
$set_bit = $res & (~( $res - 1));
$x = 0;
$y = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $arr [ $i ] & $set_bit )
$x = $x ^ $arr [ $i ];
else
$y = $y ^ $arr [ $i ];
}
echo ( $x . " " . $y );
}
$arr = array ( 2, 3, 3, 4, 4, 5 );
$n = sizeof( $arr );
printOdds( $arr , $n );
?>
|
Javascript
<script>
function printOdds(arr, n)
{
let res = 0;
for (let i = 0; i < n; i++)
res = res ^ arr[i];
let set_bit = res & (~(res - 1));
let x = 0, y = 0;
for (let i = 0; i < n; i++)
{
if (arr[i] & set_bit)
x = x ^ arr[i];
else
y = y ^ arr[i];
}
document.write(x + " " + y);
}
let arr = [ 2, 3, 3, 4, 4, 5 ];
let n = arr.length;
printOdds(arr, n);
</script>
|
Complexity Analysis:
- Time Complexity : O(n)
- Auxiliary Space : O(1)
Another Efficient Solution (Using binary search) : Sort the array for binary search . Then we can find frequency of all array elements using binary search function . Then we can check if frequency of array element is odd or not , If frequency is odd , then print that element .
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printOdds( int arr[], int n)
{
int count = 0;
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)
{
cout << arr[i]<< " " ;
}
}
}
int main()
{
int arr[] = { 2, 3, 3, 4, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
printOdds(arr, n);
return 0;
}
|
Python3
def printOdds(arr, n):
count = 0
arr.sort()
i = 0
while i < n:
first_index = arr.index(arr[i])
last_index = len (arr) - arr[:: - 1 ].index(arr[i]) - 1
i = last_index
fre = last_index - first_index + 1
if fre % 2 ! = 0 :
print (arr[i], end = ' ' )
i + = 1
arr = [ 2 , 3 , 3 , 4 , 4 , 5 ]
n = len (arr)
printOdds(arr, n)
|
Javascript
function printOdds(arr, n) {
let count = 0;
arr.sort();
let i = 0; let ans= "" ;
while (i < n) {
let first_index = arr.indexOf(arr[i]);
let last_index = arr.lastIndexOf(arr[i]);
i = last_index;
let fre = last_index - first_index + 1;
if (fre % 2 !== 0) {
ans = ans + arr[i] + " " ;
}
i += 1;
}console.log(ans);
}
let arr = [2, 3, 3, 4, 4, 5];
let n = arr.length;
printOdds(arr, n);
|
C#
using System;
public class GFG {
static void printOdds( int [] arr, int n)
{
int count = 0;
Array.Sort(arr);
int i = 0;
string ans = "" ;
while (i < n) {
int first_index = Array.IndexOf(arr, arr[i]);
int last_index = Array.LastIndexOf(arr, arr[i]);
i = last_index;
int fre = last_index - first_index
+ 1;
if (fre % 2 != 0) {
ans = ans + arr[i] + " " ;
}
i += 1;
}
Console.WriteLine(ans);
}
public static void Main()
{
int [] arr = new int [] { 2, 3, 3, 4, 4, 5 };
int n = arr.Length;
printOdds(arr, n);
}
}
|
Java
import java.util.*;
class Main {
static void printOdds( int [] arr, int n)
{
int count = 0 ;
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++) {
int first_index
= Arrays.binarySearch(arr, arr[i]);
int last_index = first_index;
if (first_index < 0 ) {
continue ;
}
while (last_index + 1 < n
&& arr[last_index + 1 ] == arr[i]) {
last_index++;
}
i = last_index;
int fre = last_index - first_index
+ 1 ;
if (fre % 2 != 0 ) {
System.out.print(arr[i] + " " );
}
}
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , 3 , 4 , 4 , 5 };
int n = arr.length;
printOdds(arr, n);
}
}
|
Time Complexity: O(n*log2n), take log2n time for binary search function
Auxiliary Space: O(1)
Similar Reads
Sum of all even occurring element in an array
Given an array of integers containing duplicate elements. The task is to find the sum of all even occurring elements in the given array. That is the sum of all such elements whose frequency is even in the array. Examples: Input : arr[] = {1, 1, 2, 2, 3, 3, 3}Output : 6The even occurring element are
12 min read
Unique element in an array where all elements occur k times except one
Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.Examples: Input : arr[] = {6, 2, 5, 2, 2, 6, 6} k = 3Output : 5Explanation: Every element appears 3 times accept 5. Input : arr[] = {2, 2, 2, 10, 2} k = 4Output: 10Explanation: Every eleme
13 min read
Find the Kth occurrence of an element in a sorted Array
Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
15+ min read
Find the elements appearing even number of times in an Array
Given an array arr[] consisting of N positive numbers in the range [1, N], the task is to print the array elements which appear even number of times in the given array. Example : Input: N = 8, arr[] = {4, 4, 2, 4, 8, 2, 3, 4}Output: [2, 4]Explanation: The numbers 2 and 4 appear even number of times
10 min read
Program to print Sum of even and odd elements in an array
Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index position
13 min read
Find even occurring elements in an array of limited range
Given an array that contains odd number of occurrences for all numbers except for a few elements which are present even number of times. Find the elements which have even occurrences in the array in O(n) time complexity and O(1) extra space. Assume array contain elements in the range 0 to 63. Exampl
8 min read
Sum of all odd frequency elements in an array
Given an array of integers containing duplicate elements. The task is to find the sum of all odd occurring elements in the given array. That is the sum of all such elements whose frequency is odd in the array. Examples: Input : arr[] = {1, 1, 2, 2, 3, 3, 3} Output : 9 The odd occurring element is 3,
8 min read
Make all the elements of array even with given operations
Given an array arr[] of positive integers, find the minimum number of operations required to make all the array elements even where: If there is an odd number, then, increment the element and the next adjacent element by 1.Each increment costs one operation. Note: If there is any number in arr[] whi
6 min read
Program to print product of even and odd indexed elements in an Array
Given an array of integers. The task is to write a program to find the product of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: Input : arr = {1, 2, 3, 4, 5, 6} Output :
9 min read
Count of even and odd set bit Array elements after XOR with K for Q queries
Given an array arr of N elements and another array Q containing values of K, the task is to print the count of elements in the array arr with odd and even set bits after its XOR with each element K in the array Q. Examples: Input: arr[] = { 2, 7, 4, 5, 3 }, Q[] = { 3, 4, 12, 6 } Output: 2 3 3 2 2 3
7 min read