Single element using Binary Search

PHOTO EMBED

Mon May 20 2024 10:37:33 GMT+0000 (Coordinated Universal Time)

Saved by @ayushg103 #c++

if(n==1)return v[0];
if(v[0]!=v[1])return v[0];
if(v[n-1]!=v[n-2])return v[n-1];
low=1;high=n-2;
while(low<high)
  {
    mid=high-((high-low)/2);
    if(v[mid]!=v[mid-1] && v[mid]!=v[mid+1])return v[mid];
    if((mid%2==0 && v[mid-1]==v[mid]) || (mid%2==1 && v[mid+1]==v[mid]))
      {
        high=mid-1;
      }
    else if((mid%2==1 && v[mid-1]==v[mid]) || (mid%2==0 && v[mid+1]==v[mid]))
      {
        low=mid+1;
      }
  }
  
content_copyCOPY

If we are standing on Even index and at next there is same element then our single element is on right half; (even,odd) -> right half (odd,even) -> left half In binary search , we may face issue of left right in extreme ends . for this ignore first and last index and check separately.