How to find the one integer that appears an odd number of times in a JavaScript array?


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 −

Example

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.

Output

The console output will be −

1

Updated on: 18-Aug-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements