DEV Community

Divyajyoti Ukirde
Divyajyoti Ukirde

Posted on • Updated on

Easy peasy First Odd Int

In a given array, find the first integer that appears an odd number of times. Given that only one integer occurs odd number of times.

One line solution to this is by using the infamous reduce operation of Javascript.

const findOddInt = (arr) => arr.reduce((a, b) => a ^ b);
Enter fullscreen mode Exit fullscreen mode

Always go for functional and tuned solution, reason it being faster ;)

For those who are wondering, ^ is the symbol for XOR. a^a = 0 and 0^a = a. So, all the numbers that occur even times will get reduced to 0 and the number that occurs odd number of times would remain.

Latest comments (2)

Collapse
 
dry profile image
Hayden Mankin

Correct me if I misunderstood, but the question is to find the first integer that appears an odd number of times. Wouldn't this solution not work if there are multiple integers appearing an odd number of times?

For instance, findOddInt([1,1,2,2,2,3,3,3]) would return 1 instead of the expected value of 2.

The solution I came up with is:

const findOddInt = (array) => {
  return Object.entries(array.reduce((oddMap, element) => {
    oddMap[element] ^= true;
    return oddMap;
  }, {})).find(element => element[1])[0];
}
Enter fullscreen mode Exit fullscreen mode

But even this I still think the problem is somewhat unclear; Should findOddInt([1,2,2,2,1,1]) return '1' because '1' appeared initially before '2', or should it be '2' because it was the first to appear an odd number of times?

Collapse
 
divyajyotiuk profile image
Divyajyoti Ukirde

Very well done! The question should be changed to only one integer occurs odd number of times