Find first and last occurrence of x

PROBLEM :

Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.

Examples:

Input : A[] = {1, 3, 5, 5, 5, 5 ,67, 123, 125}  
        x = 5
Output : First Occurrence = 2
         Last Occurrence = 5

Input : A[] = {1, 3, 5, 5, 5, 5 ,7, 123 ,125 }  
        x = 7
Output : First Occurrence = 6
         Last Occurrence = 6

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array. Then in the next line are N space separated values of the array. The last line of each test case contains an integer x.

Output:
For each test case in a new line print two integers separated by space denoting the first and last occurrence of the element x. If the element is not present in the array print -1.

Constraints:
1<=T<=101
1<=N<=100
1<=A[],k<=100

Example:
Input:
2
9
1 3 5 5 5 5 67 123 125
5
9
1 3 5 5 5 5 7 123 125
7

Output:
2 5
6 6

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#define max 100
int Occurence(int [],int ,int ,bool ) ;
int main()
{
int arr[max] ;
int k,i,no,t ;
int first,second ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
       cin>>arr[i] ;
   cin>>k ;
 
   first=Occurence(arr,no,k,true) ;
   second=Occurence(arr,no,k,false) ;
   if(first==-1&&second==-1)
       cout<<-1<<endl ;
   else
       cout<<first<<" "<<second<<endl ;
}
return 0;
}

int Occurence(int arr[],int no,int ele,bool flag)
{
    int start,end,mid,result ;
    start=0 ;
    end=no-1 ;
    result=-1 ;
   
    while(start<=end)
    {
        mid=(start+end)/2 ;
        if(arr[mid]==ele)
        {
            result=mid ;
            if(flag)
                end=mid-1 ;
            else
                start=mid+1 ;
        }
        else if(arr[mid]>ele)
            end=mid-1 ;
        else
            start=mid+1 ;
    }
    return result ;
}

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

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 )