First and last occurrences of x | Practice | GeeksforGeeks

Given a sorted array arr containing n elements with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
Example 1:
Input:
n=9, x=5
arr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }
Output:  2 5
Explanation: First occurrence of 5 is at index 2 and last
             occurrence of 5 is at index 5. 

 
Example 2:
Input:
n=9, x=7
arr[] = { 1, 3, 5, 5, 5, 5, 7, 123, 125 }
Output:  6 6 


Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function find() that takes array arr, integer n and integer x as parameters and returns the required answer.
Note: If the number x is not found in the array just return both index as -1.
 
Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1).
 
Constraints:
1 ≤ N ≤ 107
 
0
rahulvishwas26027 hours ago
// { Driver Code Starts#include<bits/stdc++.h>using namespace std;
// } Driver Code Endsvector<int> find(int arr[], int n , int x ) vector<int> v;   int index=-1;   for(int i=0;i<n;i++){       if(arr[i]==x){           index=i;           v.push_back(index);           break;       }   }   for(int i=n-1;i>=0;i--){       if(arr[i]==x){           index=i;           v.push_back(index);           break;       }   }   if(index==-1){       v.push_back(-1);       v.push_back(-1);       return v;   }   else    return v;}
0
darshananimus3 days ago

import java.io.*;
import java.util.*;

// } Driver Code Ends
//User function Template for Java

class GFG
{
   static int checkOc(long[] arr,int low, int high,int key,int type)
   {
       int res=-1;
       while(low<=high)
       {
           int mid =(low+high)/2;
           if(arr[mid]<key)
               low=mid+1;
           else if(arr[mid]>key)
               high=mid-1;
           else
           {
               if(type==1)
               {
                   res = mid;
                   high=mid-1;
               }
               else
               {
                   res=mid;
                   low=mid+1;
               }
           }
       }
       return res;
   }
   ArrayList<Long> find(long arr[], int n, int x)
   {
       int low=0,high=n-1;
       ArrayList<Long> al = new ArrayList<Long>();
       al.add((long)-1);
       al.add((long)-1);
       al.add(0,(long)checkOc(arr,low,high,x,1));//find first occurence
       al.add(1,(long)checkOc(arr,low,high,x,2));//find last occurence
       return al;
   }
}

0
darshananimus
This comment was deleted.
0
rahuljaiswalmzp3 days ago
EASY UNDERSTAND C++ SOLUTION
 
 vector<int>v;   for(int i = 0;i<n;i++){       if(arr[i]==x){           v.push_back(i);           break;       }   }     for(int i = n-1;i>=0;i--){       if(arr[i]==x){           v.push_back(i);           break;       }   }   if(v.empty()){       v.push_back(-1);        v.push_back(-1);   }   return v;
+1
harshscode4 days ago
 vector<int> v;     int f=0;      for(int i=0;i<n;i++)      {          if(a[i]==x)          {              v.push_back(i);              f++;              break;                        }      }            for(int i=n-1;i>=0;i--)      {          if(a[i]==x)          {              v.push_back(i);              f++;              break;          }      }      if(f==2)      return v;      else      {          v.push_back(-1);          v.push_back(-1);          return v;      }
0
shubhamshrivas14 days ago
def find(arr,n,x):   # code here   if x not in arr:       return (-1,-1)   b = arr.index(x)   c = arr.index(x)-1   for i in arr:       if i==x:           c+=1              return (b,c) 
0
pawancoding00115 days ago
 
Time Complexity: O(logN)
//First occurrences of x
 vector<int>v;   // code here   int l=0,h=n-1;   while(l<=h)   {       int mid=l+(h-l)/2;       if(arr[mid]>x)h=mid-1;       else if(arr[mid]<x)l=mid+1;       else       {           if(mid==0||arr[mid]!=arr[mid-1])           {v.push_back(mid);               break;           }           else           h=mid-1;       }   }
///Last occurrences of x
 l=0,h=n-1;    while(l<=h)   {       int mid=l+(h-l)/2;       if(arr[mid]>x)h=mid-1;       else if(arr[mid]<x)l=mid+1;       else       {           if(mid==n-1||arr[mid]!=arr[mid+1])           {               v.push_back(mid);break;           }           else           l=mid+1;       }   }   if(v.size()==0)   {       v.push_back(-1);       v.push_back(-1);   }   return v;
 
0
reshukumari7861 week ago
vector<int> find(int arr[], int n, int x)
{
	// code here
    int a=lower_bound(arr, arr+n, x)-arr;
    int b=upper_bound(arr, arr+n, x)-arr;
    if(n==0 || arr[a]!=x || arr[b-1]!=x)
    {
        return {-1,-1};
    }
    else
    return {a,b-1};
}
0
sumitk071 week ago
vector<int>v;
    for(int i = 0;i<n;i++){
        if(x==arr[i]){
            v.push_back(i);
            break;
        }
    }
    for(int i = n-1;i>=0;i--){
        if(x==arr[i]){
            v.push_back(i);
            break;
        }
    }
    if(v.size()==0){
        v.push_back(-1);
        v.push_back(-1);
    }
    return v;
0
kssaini32011 week ago
C++ solution
 
vector<int> find(int arr[], int n , int x ){   // code here   int flag = 0;   vector<int> dup;   vector<int> store;   sort(arr,arr+n);   for(int i=0;i<n;i++)   {       if(x == arr[i])       {           flag = 1;           dup.push_back(i);       }       }      if(flag == 1)   {       int x = *min_element(dup.begin(),dup.end());       int y = *max_element(dup.begin(),dup.end());       store.push_back(x);       store.push_back(y);       return store;   }   else   {       store.push_back(-1);       store.push_back(-1);       return store;   }   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.