<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p>

<p>Return <em>the single element that appears only once</em>.</p>

<p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8]
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11]
<strong>Output:</strong> 10
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

//binary search
class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        //1 1 2 2 3 3 4 5 5 6 6
        //  left     | |  right
        //(even,odd) pair means left, (odd,even) pair means right 
        //element is on right       , element is on left

        int n=nums.size();
        if(n==1) return nums[0];
        //trim down the search space and check separately
        if(nums[0]!=nums[1]) return nums[0];
        if(nums[n-1]!=nums[n-2]) return nums[n-1];

        int low=1;
        int high=n-2;

        while(low<=high){
            int mid=(low+high)/2;
            //if mid ele is single
            if(nums[mid]!=nums[mid+1] && nums[mid]!=nums[mid-1]){
                return nums[mid];
            }
            //if we at odd index - EVEN ODD same no. situation - single ele not in left half
            //you might be here     ^ or ^ here but both indicate that left half is clean so trim
            //0 1 2 3 4 5 6 7 8 9 10
            //1 1 2 2 3 3 4 5 5 6 6
            //  ^     ^ ^       ^  
            //left ele is equal to curr then that means we are on left half
            //OR right ele is equal to curr then same situation, as long as odd index
            if((mid%2==1 && nums[mid]==nums[mid-1])
             ||(mid%2==0 && nums[mid]==nums[mid+1])){
                low=mid+1;//eliminate left half
            }
            //we in right half so eliminate right half
            else{
                high=mid-1;
            }
        }
        return -1;
    }
};

25000