Explanation of XOR Logic:
The XOR operation (^
) has the following properties that make it ideal for this problem:
- Identity Property:
a ^ a = 0
(XOR of a number with itself is 0) - Commutative Property:
a ^ b = b ^ a
(Order of operation doesn’t matter) - Associative Property:
(a ^ b) ^ c = a ^ (b ^ c)
(Grouping of operations doesn’t matter) - Identity with Zero:
a ^ 0 = a
(XOR with 0 leaves the number unchanged)
Given that the employee IDs in the array appear exactly twice (except for the missing employee who hasn’t exited), XORing all the IDs together will cancel out the IDs that appear twice, leaving only the ID that appears once (the missing one).
How the Code Works:
- Initialization: We initialize
result = 0
. As we XOR all the IDs, theresult
will accumulate the final XOR value. - Iterating through the array: For each ID in the array, we XOR it with
result
. IDs that appear twice will cancel each other out, and the one ID that appears once will remain inresult
. - Return the result: The result after the loop ends will be the missing employee ID (the one that doesn’t have a matching pair).
Code Walkthrough:
#include <stdio.h>
// Function to find the missing employee ID using XOR
int findMissingFingerprint(int arr[], int size) {
int result = 0;
for (int i = 0; i < size; i++) {
result ^= arr[i]; // XOR each element with the result
}
return result; // After all XOR operations, only the missing ID will remain
}
int main() {
// Array of employee IDs (each appears twice except the missing one)
int fingerprints[] = {1, 4, 3, 2, 4, 5, 2, 1, 3};
int size = sizeof(fingerprints) / sizeof(fingerprints[0]);
// Finding the missing employee ID
int missing = findMissingFingerprint(fingerprints, size);
// Printing the missing employee ID
printf("Employee number: %dn", missing);
return 0;
}
Output:
Employee number: 5
Explanation of the Example:
- The input array is
{1, 4, 3, 2, 4, 5, 2, 1, 3}
. - After XORing all the elements:
1 ^ 4 ^ 3 ^ 2 ^ 4 ^ 5 ^ 2 ^ 1 ^ 3 = 5
- All pairs of IDs (like
1 ^ 1
,4 ^ 4
,3 ^ 3
,2 ^ 2
) cancel out to0
, leaving the ID5
, which is the employee who hasn’t exited.
Time Complexity:
- O(n) where
n
is the size of the array. We iterate through the array once, performing constant time operations (XOR).
Space Complexity:
- O(1) because we are only using a constant amount of extra space (
result
).
This is an optimal solution both in terms of time and space.