You are given a sorted array 'arr' of positive integers of size 'n'.
It contains each number exactly twice except for one number, which occurs exactly once.
Find the number that occurs exactly once.
Input: ‘arr’ = {1, 1, 2, 3, 3, 4, 4}.
Output: 2
Explanation: 1, 3, and 4 occur exactly twice. 2 occurs exactly once. Hence the answer is 2.
The first line contains an integer ‘n’, representing the size of the array ‘arr’.
The second line contains ‘n’ integers, denoting the elements of the array ‘arr’.
The output contains the integer in the array that occurs exactly once.
You do not need to print anything; it has already been taken care of. Just implement the given function.
5
1 1 2 2 3
3
{1, 2} each occurs twice, whereas 3 occurs only once.
Hence the answer is 3.
5
8 8 9 9 10
10
The expected time complexity is O(n), but try solving it in O(log n).
1 <= 'n' <= 10^4
1 <= 'arr[i]' <= 10^9
‘n’ is always odd.
Time Limit: 1 sec
Think of the most simple way to find out if there is another number equal to the current number in an array.
Approach:
We can iterate through the array and then for each element we find out if there is another element equal to the current element by iterating through the elements once again.
Algorithm:
O(n ^ 2), where ‘n’ is the number of elements in the array ‘arr’.
We are iterating via ‘i’ from 0 to ‘n - 1’ and for each ‘i’, we are iterating via ‘j’ from 0 to ‘n - 1’, hence the overall time complexity of this solution is O(n ^ 2).
O(1)
We are not utilizing any extra space, hence the overall space complexity of this solution is O(1).