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]

Understanding XOR Operator

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

Key Properties of XOR

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 0. This means it can be used to negate values that make appearance for even number of times. And that's exactly what we want.

// Demonstrating XOR properties
console.log(5 ^ 5);    // 0 (same numbers cancel out)
console.log(7 ^ 7);    // 0
console.log(0 ^ 3);    // 3 (XOR with 0 returns the number)
console.log(3 ^ 5 ^ 3); // 5 (3 appears twice, cancels out)
0
0
3
5

Solution Using XOR

The solution leverages the fact that XOR of identical numbers is 0, and XOR of any number with 0 is the number itself. When we XOR all elements, pairs cancel out leaving only the odd-occurrence element.

const sampleArray = [1, 4, 3, 4, 2, 3, 2, 7, 8, 8, 9, 7, 9];
console.log("Array:", sampleArray);

// Using reduce with XOR operator
const result = sampleArray.reduce((a, b) => a ^ b);
console.log("Element appearing odd times:", result);
Array: [1, 4, 3, 4, 2, 3, 2, 7, 8, 8, 9, 7, 9]
Element appearing odd times: 1

Alternative Implementation

function findOddOccurrence(arr) {
    let result = 0;
    for (let i = 0; i < arr.length; i++) {
        result ^= arr[i];
    }
    return result;
}

const testArray = [2, 3, 5, 4, 5, 3, 4];
console.log("Odd occurrence element:", findOddOccurrence(testArray));
Odd occurrence element: 2

How It Works

It iterates over each element and keeps negating the elements that make even appearances using XOR. Since identical numbers XOR to 0, all even-occurrence elements cancel out, and only the element that appears for an odd number of times is returned.

Conclusion

The XOR approach provides an elegant O(n) time and O(1) space solution to find the odd-occurrence element. This method works because XOR of identical numbers equals zero, effectively canceling out all even-occurrence elements.

Updated on: 2026-03-15T23:18:59+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements