DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 77

The task is to implement a function that quickly targets an integer that appears once, given an array of integers that appear twice.

The boilerplate code

function findSingle(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The single integer can be quickly targeted using the XOR trick (^). Using the example

a ^ a = 0
Enter fullscreen mode Exit fullscreen mode

Two numbers that are the same cancel out. So, using the XOR method, all numbers in pairs will cancel out.

for(let num of arr) {
 result ^= num
}
Enter fullscreen mode Exit fullscreen mode

Then the remaining integer is returned. The final code:

function findSingle(arr) {
  // your code here
  let result = 0;

  for(let num of arr) {
    result ^= num;
  }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)