Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C/C++ Program for Finding the Number Occurring Odd Number of Times?
In C programming, finding the number that occurs an odd number of times in an array is a common problem. Given an array where all elements appear an even number of times except one, we need to identify that unique element.
Consider the array [1, 2, 1, 3, 3, 2, 2]. Here, the number 2 appears 3 times (odd), while others appear even times.
Example Scenarios
Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7
The number 7 appears 3 times (odd frequency).
Input: arr[] = {2, 3, 2, 1, 1, 4, 4}
Output: 3
The number 3 appears once (odd frequency).
Method 1: Naive Approach
The straightforward approach uses nested loops to count each element's frequency. If the count is odd, that element is our answer −
#include <stdio.h>
int findOddOccurring(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++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
int main() {
int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Element occurring odd times: %d\n", findOddOccurring(arr, n));
return 0;
}
Element occurring odd times: 7
Time Complexity: O(n²) | Space Complexity: O(1)
Method 2: Bitwise XOR Approach
The optimal solution uses XOR operation. Since XOR of identical numbers is 0 and XOR with 0 returns the original number, all even-occurring elements cancel out, leaving only the odd-occurring element −
#include <stdio.h>
int findOddOccurring(int arr[], int n) {
int result = 0;
for (int i = 0; i < n; i++) {
result = result ^ arr[i];
}
return result;
}
int main() {
int arr[] = {2, 3, 2, 1, 1, 4, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Element occurring odd times: %d\n", findOddOccurring(arr, n));
return 0;
}
Element occurring odd times: 3
Time Complexity: O(n) | Space Complexity: O(1)
How XOR Works
The XOR approach works because of these properties:
-
a ^ a = 0(any number XOR with itself is 0) -
a ^ 0 = a(any number XOR with 0 is the number itself) - XOR is commutative and associative
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Naive Approach | O(n²) | O(1) | Small arrays, educational purposes |
| XOR Approach | O(n) | O(1) | Large arrays, production code |
Conclusion
The XOR-based approach is the optimal solution for finding elements occurring odd times, offering linear time complexity with constant space. It elegantly leverages bitwise properties to solve the problem efficiently.
