Given an array of positive integers. All numbers occur even number of times except one number which occurs the 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
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));
}
}
|
Time Complexity : O(n^2)
Auxiliary Space: O(1)
A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
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));
}
}
|
Please refer complete article on Find the Number Occurring Odd Number of Times for more details!
Last Updated :
31 May, 2022
Like Article
Save Article
Vote for difficulty