Find the element that appears once in sorted array

PROBLEM :

Given a sorted array of integers, every element appears twice except for one. Find that single one in linear time complexity and without using extra memory.

Input:
The first line of input consists number of the test cases. The description of T test cases is as follows:
The first line of each test case contains the size of the array, and the second line has the elements of the array.

Output:
In each separate line print the number that appears only once in the array.

Constraints:
1 = T = 70
1 = N = 100
0 = A[i] = 100000

Example:
Input:
1
11
1 1 2 2 3 3 4 50 50 65 65

Output:
4

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( O(n) Solution using Bitwise)
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;

int main()
{
int t ;
cin>>t ;
while(t--)
{
   int no ;
   cin>>no ;
 
   int arr[no] ;
   for(int i=0;i<no;i++)
       cin>>arr[i] ;
     
   int XOR=0 ;
   for(int i=0;i<no;i++)
       XOR=XOR^arr[i] ;
     
   cout<<XOR<<endl ;
}
return 0;
}

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( O(Logn) Solution using Binary Search)
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int FindElement(int [],int ,int ) ;
int main()
{
int t ;
cin>>t ;
while(t--)
{
   int no ;
   cin>>no ;
 
   int arr[no] ;
   for(int i=0;i<no;i++)
       cin>>arr[i] ;
     
   cout<<FindElement(arr,0,no-1)<<endl ;
}
return 0;
}

int FindElement(int arr[],int start,int end)
{
    if(start>end)
        return -1 ;
       
    if(start==end)
        return arr[start] ;
       
    int mid=(start+end)/2 ;
   
    if(mid%2==0)
    {
        if(arr[mid]==arr[mid+1])
            return FindElement(arr,mid+2,end) ;
        else
            return FindElement(arr,start,mid) ;
    }
    else
    {
        if(arr[mid]==arr[mid-1])
            return FindElement(arr,mid+1,end) ;
        else
            return FindElement(arr,start,mid-1) ;
    }
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )