Fetching odd appearance number in JavaScript

Given an array of integers, we need to find the element that appears an odd number of times. There will always be exactly one such element.

We can solve this problem using different approaches. The sorting approach iterates through a sorted array to count occurrences, while XOR provides an elegant mathematical solution.

Method 1: Using Sorting

This approach sorts the array first, then iterates through it to count consecutive identical elements.

const arr = [20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5];

const findOddSorting = arr => {
    let count = 0;
    let last;
    arr.sort((a, b) => a - b);
    
    for (let i = 0; i 

5

Method 2: Using XOR Operation

XOR has a unique property: any number XORed with itself equals 0, and 0 XORed with any number equals that number. Elements appearing an even number of times cancel out.

const arr2 = [20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5];

const findOddXOR = arr => {
    let result = 0;
    for (let num of arr) {
        result ^= num;
    }
    return result;
};

console.log(findOddXOR(arr2));
5

Method 3: Using Map to Count Occurrences

This approach uses a Map to count each element's frequency, then finds the one with odd count.

const arr3 = [20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5];

const findOddMap = arr => {
    const countMap = new Map();
    
    for (let num of arr) {
        countMap.set(num, (countMap.get(num) || 0) + 1);
    }
    
    for (let [num, count] of countMap) {
        if (count % 2 === 1) {
            return num;
        }
    }
};

console.log(findOddMap(arr3));
5

Comparison

Method Time Complexity Space Complexity Pros
Sorting O(n log n) O(1) Easy to understand
XOR O(n) O(1) Most efficient, elegant
Map O(n) O(n) Clear logic, handles any count

Conclusion

The XOR method is most efficient with O(n) time and O(1) space complexity. Use the Map approach when you need to handle more complex counting scenarios.

Updated on: 2026-03-15T23:19:00+05:30

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements