- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

1

- Related Questions & Answers
- Take an array and find the one element that appears an odd number of times in JavaScript
- Finding number that appears for odd times - JavaScript
- Get the item that appears the most times in an array JavaScript
- Return the element that appears for second most number of times in the array JavaScript
- Number of times a string appears in another JavaScript
- Counting how many times an item appears in a multidimensional array in JavaScript
- Find the element that appears once in sorted array - JavaScript
- Java Program to Find the Number Occurring Odd Number of Times
- C/C++ Program to Find the Number Occurring Odd Number of Times?
- Find the number of times a value of an object property occurs in an array with JavaScript?
- Find the element that appears once in an array where every other element appears twice in C++
- Python Program to Find Element Occurring Odd Number of Times in a List
- How to make a function that returns the factorial of each integer in an array JavaScript
- MySQL query to count the number of times a specific integer appears in a column for its corresponding value in another column
- Program to find how many times a character appears in a string in PHP

Advertisements