We are given an array of integers and told that all the elements appear for an even number of times except a single element. Our job is to find that element in single iteration.
Let this be the sample array −
[1, 4, 3, 4, 2, 3, 2, 7, 8, 8, 9, 7, 9]
Before attempting this problem, we need to understand a little about the bitwise XOR (^) operator.
The XOR operator returns TRUE if both the operands are complementary to each other and returns FALSE if both the operands are the same.
TRUTH TABLE OF XOR () operator −
0 ^ 0 → 0 0 ^ 1 → 1 1 ^ 0 → 1 1 ^ 1 → 0
If we closely examine this behavior, we can notice that when the XOR operator is used on exact same values (e.g., 12^12) it always returns FALSE or 0 in other words it can be used to negate values that makes appearance for even number of times. And that’s exactly what we want.
So, writing the same in the below code −
const sampleArray = [1, 4, 3, 4, 2, 3, 2, 7, 8, 8, 9, 7, 9]; console.log(sampleArray.reduce((a, b) => a ^ b));
It iterates over each element and keeps negating the elements that make even appearances and the only element that appears for an odd number of times is returned.
The console output will be −
- Related Articles
- First element that appears even number of times in an array in C++
- Java Program to Find the Number Occurring Odd Number of Times
- Find the element that appears once in an array where every other element appears twice in C++
- C/C++ Program to Find the Number Occurring Odd Number of Times?
- MySQL query to count the number of times a specific integer appears in a column for its corresponding value in another column
- Find the only element that appears b times using C++