Welcome to CodeYourCraft! Today, we're going to learn a fascinating algorithm that helps us find two odd numbers that occur an odd number of times in an array. This technique is useful in data analysis, debugging, and many other areas of programming.
Let's break down the problem, understand it, and then we'll dive into the solution.
Given an array of integers, the task is to find two numbers that occur an odd number of times.
Here are a few things to note about this problem:
The algorithm we'll use is based on Bitwise XOR (^) and a concept called "Finding Set Bit Count" (which we'll learn shortly). Here's a high-level overview of the algorithm:
Let's delve into each step.
When we XOR two identical numbers, the result is 0. When we XOR an odd number with another odd number, the result contains a set bit at a unique position. If we XOR all the numbers in the array, all the odd numbers' unique bits will be set, and all the even numbers will be eliminated.
Now that we have the XOR result, we need to find out how many set bits it contains. This is known as the Set Bit Count or Population Count (popcount). We'll learn an efficient way to calculate the set bit count using Bitwise AND and Bit Shift operations.
With the set bit count, we can find two numbers that have a difference equal to the half of the set bit count. We then iterate through the array and find the two numbers that match this condition.
Now, let's put it all together in Python:
def findTwoOddOccurringNumbers(arr):
result = [0] * 32
# Calculate set bit count for each number in the array
for num in arr:
for i in range(32):
if (num & (1 << i)):
result[i] += 1
# Find the XOR of all set bits
xor = 0
for bit in result:
xor ^= bit
# Find the number of set bits in the XOR
set_bits = 0
while xor:
xor &= xor - 1
set_bits += 1
# Find the half of set bits and the index with the set bit
half = set_bits // 2
mask = 1 << half
# Find the two numbers that have the half set bit
first_num = -1
second_num = -1
for num in arr:
if (num & mask):
if first_num == -1:
first_num = num
else:
second_num = num
break
# In case the array only has one odd number
if second_num == -1:
second_num = first_num ^ arr[0]
return first_num, second_num
arr = [1, 2, 2, 3, 3, 3, 4, 5, 5]
print(findTwoOddOccurringNumbers(arr)) # Output: (3, 4)Now that you understand the algorithm, let's test your knowledge with a quiz:
What is the output of the `findTwoOddOccurringNumbers` function for the following array: `[1, 2, 3, 4, 4, 5, 5, 6, 6, 7]`
Congratulations on completing this lesson on finding two odd occurring numbers! If you have any questions or need further clarification, feel free to ask. Happy coding! š