Equal Point in Sorted Array

PROBLEM :
Given a sorted array A of size N, the task is to find whether an element exists in the array from where number of smaller elements is equal to number of greater elements. If Equal Point appears multiple times in input array, print the index of its first occurrence. If Equal Point doesn't exists then print -1.

Examples :

Input  : arr[] = {1, 2, 3, 3, 3, 3}
Output : 1
Equal Point is arr[1] which is 2. Number of
elements smaller than 2 and greater than 2
are same.

Input  : arr[] = {1, 2, 3, 3, 3, 3, 4, 4}
Output : -1

Input : arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}
Output : 3
First occurrence of equal point is arr[3]

Input:
The first line of input contains T denoting the no of test cases . Then T test cases follow . The first line of each test case contains an Integer N and the next line contains N space separated values of the array A[ ] .

Output:
For each test case output the required result in a new line.

Constraints:
1<=T<=100
1<=N<=100
1<=A[ ] <=100

Example:
Input:
2
6
1 2 3 3 3 3
8
1 2 3 3 3 3 4 4

Output:
1
-1

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

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

int Equal_Point_Sorted_Array(int arr[],int no)
{
    int count,i ;
    count=1 ;
   
    for(i=0;i<no-1;i++)
    {
        if(arr[i]!=arr[i+1])
            count++ ;
    }
       
    if(count%2==0)
        return -1 ;
       
    int mid=count/2   ;
   
    i=0 ;
    while(mid)
    {
        if(arr[i]!=arr[i+1])
            mid-- ;
        i++ ;
    }
   
    return i ;
}

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

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 )