You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in
Output: 2
Output: 10
Constraints:
1 <= nums.length <= 105 0 <= nums[i] <= 105
Contents
Solution 1 - Using binary search
As per the problem statement, every element in input array appeared twice except one element, that means the input array must be an odd length array, and this is the key to solve this problem. In this approach we will apply binary search algorithm to find that unique element.
We will create two pointers
-
Check if the element at
mid index is not equal to its neighbours, then return themid element. -
If the
mid element is not unique, that means either left neighbor or right neighbour element value also same, so after ignoring currentb-v and one of its neighbour which has same value, get the reamining array length on left side and right sides, and one of these arrays must be odd length, because if every element appeared two times except one element, that side of array must be odd length. -
If left side of array is odd length, then we will update
right pointer tomid-1 . -
If right side of array is odd length, then we will update
left pointer tomid+1 .
Complexity Analysis:
Time complexity: Above code runs in O(log n) time where
Space complexity: O(1).
Above implementations source code can be found at