Given an array of integers. All numbers occur twice except one number which occurs once. Find the number in O(n) time & constant extra space.

Example 1:

Input:  arr[] = {2, 3, 5, 4, 5, 3, 4}

Output: 2

Example 2:

Input:  arr[] = {7, 3, 5, 4, 5, 3, 4}

Output: 7

We are using a binary search algorithm to find the single element in the list of duplicate elements. Before that, we need to make sure if the array is sorted. The first step is to sort the array because binary search algorithm won't work if the array is not sorted.

Now let us move to the binary search implementation:

There are two halves that are created by the only single element present in the array which are left half and right half. Now if there are duplicates present in the left half, then the 1st instance of the duplicate element in the left half is an even index and the 2nd instance is an odd index. The opposite of the left half happens in the right half(1st instance is an odd index and the second instance is the even index). Now apply the binary search algorithm:

• The solution is to take two indexes of the array(low and high) where low points to array-index 0 and high points to array-index (array size-2). We take out the mid index from the values by (low+high)/2.
• Now check if the mid-index value falls in the left half or the right half. If it falls in the left half then we change the low value to mid+1 and if it falls in the right half, then we change the high index to mid-1. To check it, we used a logic (if(arr[mid]==arr[mid ^ 1]). If mid is an even number then mid^1 will be the next odd index, and if the condition gets satisfied, then we can say that we are in the left index, else we can say we are in the right half. But if mid is an odd index, then mid^1 takes us to mid-1 which is the previous even index, which gets equal means we are in the right half or else the left half.
• This is done because the aim of this implementation is to find the single element in the list of duplicates. It is only possible if the low value is more than the high value because at that moment low will be pointing to the index that contains the single element in the array.
• After the loop ends, we return the value with a low index.

Algorithm,

const singleelement = arr  => {
arr = arr.sort(function(a,b){return a-b});

let n = arr.length;
let low = 0, high = n - 1;
let mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == arr[mid ^ 1]) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return arr[low];

}

console.log(singleelement([2, 3, 5, 4, 5, 3, 4]));
// 2

I hope you understood the algorithm, if you have any doubts let us know in the comments.