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
Python Program to Find Element Occurring Odd Number of Times in a List
When it is required to find an element that occurs odd number of times in a list, several approaches can be used. The most common methods include nested loops to count occurrences, using Python's Counter from collections module, or using XOR operations for optimization.
Method 1: Using Nested Loops
This method iterates through the list and counts occurrences of each element using nested loops ?
def odd_occurrence(my_list, list_size):
for i in range(0, list_size):
count = 0
for j in range(0, list_size):
if my_list[i] == my_list[j]:
count += 1
if (count % 2 != 0):
return my_list[i]
return -1
my_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
print("The list is:")
print(my_list)
n = len(my_list)
print("The length is:", n)
result = odd_occurrence(my_list, n)
print("The element that occurs odd number of times is:", result)
The list is: [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56] The length is: 17 The element that occurs odd number of times is: 34
Method 2: Using Counter
Python's Counter class provides a more efficient way to count occurrences ?
from collections import Counter
def find_odd_occurrence(my_list):
count_dict = Counter(my_list)
for element, count in count_dict.items():
if count % 2 != 0:
return element
return -1
my_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
print("The list is:", my_list)
result = find_odd_occurrence(my_list)
print("Element with odd occurrence:", result)
The list is: [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56] Element with odd occurrence: 34
Method 3: Using XOR Operation
For lists where only one element occurs odd times, XOR operation provides an optimal solution ?
def find_odd_using_xor(my_list):
result = 0
for element in my_list:
result ^= element
return result
# Example with only one element having odd occurrence
my_list = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 2]
print("The list is:", my_list)
result = find_odd_using_xor(my_list)
print("Element with odd occurrence:", result)
The list is: [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 2] Element with odd occurrence: 5
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops | O(n²) | O(1) | Simple implementation |
| Counter | O(n) | O(n) | Multiple odd occurrences |
| XOR Operation | O(n) | O(1) | Only one odd occurrence |
Conclusion
Use the Counter method for general cases with multiple elements having odd occurrences. The XOR method is optimal when only one element occurs odd times, while nested loops provide a straightforward but less efficient approach.
