Two Odd Occurring Elements in an Array where all Other Occur Even Times


The problem includes finding two odd occurring elements in an array where all other elements occur even times in C++. An array is a data structure in C++ which is used to store a list of elements in it of similar data types.

We will be given an array of any size greater than or equal to 2 in input. The array will contain integers in it. Every integer in the array will occur even times except two integers which will be occurring odd times in the array. In this problem, we need to find out those two elements occurring odd times in the array and print them.

The below examples will help you to understand the problem better:

Input

a[] = {2, 5, 15, 5, 9, 5, 15, 9}

Output

2  5

Explanation : In the array given 2 appears one time, 5 appears three times and 15 and 9 appears two times. Since elements occurring odd times in the array are 2 and 5 which is our answer to the problem.

Input

a[] = {10, 10, 10, 8, 3, 8, 10, 5}

Output

3 5

Explanation : The integers 10 and 8 appear even times in the given array as 10 appears 4 times and 8 appears twice. While 3 and 5 only appear once thus, 3 and 5 are two odd occurring elements in the array.

Input

a[] = {2, 4}

Output

2 4

Explanation : In the given array, there are only two distinct integers. As they both appear once, 2 and 4 will be our output.

To solve this problem, we can find different approaches and functions provided in C++. Let’s try to understand different approaches to solve the above problem from brute force to an optimised solution.

Approach-1 (Brute force)

Using nested for loops, this problem can be solved by brute force. We'll iterate through a given array from i=0 to the array's size, then through a nested loop to see if the element a[i] appears again in the array and count how many times it does. Iterate through the remaining elements if it appeared an even number of times; if it appeared an odd number of times, print the element.

The approach can be implemented by following these steps:

  • Create a function that prints all of the array's oddly occurring elements.

  • Iterate in a for loop from i=0 to the array's size to determine the occurrence of each element.

  • Declare a variable cnt to count the occurrences of element a[i] in the array.

  • Now iterate in a nested for loop from j=0 to the array’s size and check if a[i]=a[j] for any value of j less than i then break the loop to avoid checking the occurrence of an element which has already been checked. If a[i]=a[j] for any value of j greater than or equal to i, increase cnt by i to count the occurrence.

  • After traversing the whole array, check if the cnt is an odd number or even. If it is an odd number, print the particular element i.e. a[i].

  • In this way, we can print the two odd occurring elements in an array where all other elements occur even times.

The C++ code for the approach:

Example

// C++ code for finding  odd occurring elements
// in an array
#include <bits/stdc++.h>

using namespace std;

//function to print two odd occurring elements in the array
void odd_occurring(int a[], int N)
{
   cout<<"The odd occurring elements in an array are ";
   //iterating in a nested loop to check the occurrence of every element
	for (int i = 0; i < N; i++) { 
		int cnt = 0; //to count the occurrence
		for (int j = 0; j < N; j++) {
        if(a[i]==a[j] && j<i) //to avoid re-checking of the element
        {
         break;
        }
			if (a[i] == a[j]) { 
				cnt = cnt + 1; //if element appears in the array increase the count
			}
		}
		if ( cnt % 2 != 0) {   //if cnt is an odd number print the element
			cout << a[i]<< " "; 
		}
	}

}

int main()
{
	int a[] = { 12, 18, 7, 12, 7, 7, 18, 3, 9, 3 };
	int N = sizeof(a) / sizeof(a[0]);  //calculating size of the array

	odd_occurring(a, N); //calling the function
	
	return 0;
}

Output

The odd occurring elements in an array are 7 9 

Time Complexity : O(N^2) , we are iterating in a nested for loop.

Space Complexity : O(1) , since we didn’t use any extra space to solve the problem.

Approach-2 (using map)

This could be a better approach than the above one. We can use hashmap to solve the problem with an efficient approach. We will store every element present in the array as key and number of times it occurs in the array as value. Then traverse the map and check for each key i.e. element present in the array, if it appears an odd number of times print the element. This is how using hashmap we can get the two odd occurring elements in an array with less runtime.

Syntax for hashmap:

unordered_map<data type-1, datatype-2> hashmap;

To solve the problem with hashmap, follow the steps below:

  • Create a function that checks the occurrence of all the elements in the array using hashmap and prints the two oddly occurring elements.

  • We will then initialise a hashmap with the elements as keys and their occurrences as values.

  • Once all of the elements have been inserted into the map, we will iterate through it to check the occurrence of each element in the array.

  • We'll print the elements that appear an odd number of times.

The C++ code for the approach:

Example

//C++ code for finding two odd occurring elements in the array using hashmap
#include <bits/stdc++.h>

using namespace std;

//function to find the elements occurring odd times in the array using map
void odd_occurring(int a[],int N){
   
   unordered_map<int, int> hm; //to store elements and their occurrences
   
   //storing values in unordered map
   for(int i=0;i<N;i++){ 
      hm[a[i]]++;
   }
   
   cout<<"The odd occurring elements in an array are ";
   
   for(auto it:hm){
      //if occurrence of any element is odd print the element i.e. key in map
      if((it.second%2) != 0){
         cout<<it.first<<" "; 
      }
   }
}

int main()
{
   int a[]={4,1,1,21,8,1,33,21,1,33,4,2};
   
   int N = sizeof(a)/sizeof(a[0]); //calculating size of the array
   
   odd_occurring(a, N); //calling the function
   

   return 0;
}

Output

The odd occurring elements in an array are 2 8 

Time Complexity : O(N) , as we iterate in the array to store the elements and time complexity of operations of hashmap is O(N) in the worst case.

Space Complexity : O(N) , as we created an unordered map.

Approach-3 (using sort() function)

We used an extra space in the above approach. There could be an approach with O(1) space and an optimised approach to the first one. In this approach, we will be using sort() function to solve the given problem.

The sort() function sorts the array in the ascending order by default.

Syntax

sort(arr,arr+n);

The two parameters passed are the positions to sort the array in the given range.

After sorting the array, we can iterate in the array from 0 to array’s size and count the occurrence of each element therefore printing the odd occurring elements.

The approach can be applied using following steps:

  • Make a function for printing the odd occurring elements.

  • Then sort the given array using sort() function.

  • Iterate in a for loop from i=0 to i<size of array.

  • Create two variables j and cnt. j will be used to check until which index a[i] is occurring and cnt to count the number of occurrences.

  • Then iterate in a while loop until a[i]=a[j] & j<N. Keep increasing j and cnt by 1 until it satisfies this condition.

  • Store j-1 in i to avoid iteration of the same element and then check if cnt is an odd number, if it is then print the particular element.

  • We can print all the odd occurring elements present in the array in this way.

The C++ code for the approach:

Example

//C++ program to find two odd occurring elements using sort function
#include <bits/stdc++.h>

using namespace std;

//function find the odd occurring elements using sort() function
void odd_occurring(int a[],int N){
   sort(a,a+N); //sorting the array
   
   cout<<"The odd occurring elements are ";
   
   for(int i=0;i<N;i++){
      
      int j=i; //to check number of times the element is present in the array
      int cnt=0; //to count the occurrence of each element
      
      while(a[i]==a[j] && j<N){  
         cnt++;  //increase the count every time 
         j++; //increase j by 1 
      }
      i=j-1;  //store the last index we checked in i
      
      //if cnt is an odd number print the particular element
      if(cnt%2 !=0){
         cout<<a[i]<<" ";
      }
   }
}

int main()
{
   int a[]={1,3,10,3,1,1,3,10,1,5,1,5};
	int N = sizeof(a) / sizeof(a[0]);  //calculating size of the array

	odd_occurring(a, N); //calling the function


   return 0;
}

Output

The odd occurring elements are 1 3

Time Complexity : O(N*logN) , the time complexity for sort() function

Space Complexity : O(1) , because we didn't use any extra space.

Conclusion:

We talked about how to find the two odd occurring elements in an array where all other elements appear an even number of times. We learned to solve the problem in C++ using different functionalities and data structures from a naive approach to an efficient solution.

After reading the article, I hope you are clear on all of your concerns about the issue.

Updated on: 21-Aug-2023

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements