![]() |
VOOZH | about |
Given a sorted array arr[] where every element appears exactly twice except one element that appears only once, find that single element.
Examples:
Input: arr[] = [1, 1, 2, 2, 3, 4, 4]
Output: 3
Explanation: All numbers except 3 occur twice in the array.Input: arr[] = [1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8]
Output: 8
Explanation: All numbers except 8 occur twice in the array.
Table of Content
The idea behind this approach is to check every adjacent element in order to find if there exists its pair or not as the array is sorted.
3
The idea behind this approach is to use bitwise XOR between pair of elements, as XOR of two same numbers is always equal to 0.
We can use the properties of XOR (a ^ a = 0 & a ^ 0 = a) to find the element that occurs once. The idea is to find the XOR of the complete array, so all the elements which occur twice will have their XOR = 0 and the XOR of the array will be the required answer.
3
The idea is to use Binary Search. Below is an observation on the input array.
All elements before the element that occurs once have the first occurrence at even index (0, 2, ..) and the next occurrence at odd index (1, 3, ...). And all elements after the element that occurs once have the first occurrence at an odd index and the next occurrence at an even index.
3