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
 
+1
nikhil_deore1 hour ago
C++ Fast AF   0.29
 
vector<int> find(int arr[], int n , int x )
{   long count=0;
    vector<long long>ans;
  for(long long i=0;i<n;i++){
      if(arr[i]==x){
          ans.push_back(i);
          count++;
      }
  }
  if(ans.size()==0){
      return {-1,-1};
  }
   return {ans[0],ans[count-1]};
   
}
0
yashdalal452 hours ago
Binary Search Solution
Time Complexity : O(log n)
Space Complexity: O(1)
ArrayList<Long> find(long arr[], int n, int x)
   {
       // code here
       ArrayList<Long> a = new ArrayList<>();
       a.add((long)-1);  // store min index
       a.add((long)-1);  // store max index
       binary_s(arr,x,0,n-1,a);
       return a;
       
   }
   public void binary_s(long[] arr,int x,int s,int e,ArrayList<Long> a){
       if(s>e){
           return;
       }
       int mid = s+(e-s)/2;
       if(x<=arr[mid]){
           if(x==arr[mid]) {
               if(a.get(0)>mid || a.get(0)==-1) a.set(0,(long)mid);
               if(a.get(1)<mid) a.set(1,(long)mid);
               
           }
           binary_s(arr,x,s,mid-1,a);
       }
       //use if block again because in case when x==arr[mid] we have to search in both left and right part of array.
       if(x>=arr[mid]){         
           binary_s(arr,x,mid+1,e,a);
       }
   }
0
surabhichoubey5520 hours ago
 ALGO TO SOLVE THIS QUESTION 
 
based on binary search 
 
// for left occurrences
 
lets take example of given array
0 1  2  3  4  5  6   7    8    index
1, 3, 5, 5, 5, 5, 7, 123, 125 arr
 
LETS UNDERSTAND IN OUR NATIVE LANGUAGE
 
1 first find mid if equal to key to answer mai store karalo 
maybe left mai iski or bhi occurrences mil jaye 
fir ham apne end ko left mai lane ke liye
 end = mid-1 //left wala part
kr dete hain
 
2 further steps are same as binary search 
2.1 if the key, you are searching for is less than mid that means hamko left wale part pr aana hai iske liye end = mid-1 kr dete hain
 
2.2 if the key you are searching for is greater than arr[mid]
that means hamko right wale part pr search karna hai 
s = mid+1;
 
3 and yeah don't forget to update your mid
 
 
 
//for right occurrences
 
1 same as left occurence but the key point is 
if arr[mid] == key than store it in ans and go for right side
maybe we are able to find its right most occurrences 
for that start = mid + 1//right wala part
 
and furhter steps are same 
store both the answer in vector ans return happy!
// { Driver Code Starts#include<bits/stdc++.h>using namespace std;
// } Driver Code Endsvector<int> find(int arr[], int n , int key ){   // code here    vector<int>ans;   int s = 0;   int e = n-1;  int  mid = s+(e-s)/2;   int ans1 = -1;   //left occurance   while(s<=e)   {       if(arr[mid] == key)       {          ans1 = mid;          e = mid-1;       }       else if(key>arr[mid])       {           s = mid+1;       }       else if(key<arr[mid])       {           e = mid-1;       }       mid = (s+e)/2;   }   ans.push_back(ans1);   //right        int s1 = 0;       int e1 = n-1;       int  mid1 = s+(e-s)/2;       int ans2 = -1;    while(s1<=e1)   {       if(arr[mid1] == key)       {          ans2 = mid1;          s1 = mid1+1;       }       else if(key>arr[mid1])       {           s1 = mid1+1;       }       else if(key<arr[mid1])       {           e1 = mid1-1;       }       mid1 = (s1+e1)/2;   }      ans.push_back(ans2);    return ans; }
 
   
 
   
0
vijeayaetv02 days ago
Python solution.
All test cases passed.
 
def find(arr,n,x):   # code here   l1=[-1,-1]   c=arr.count(x)   if c>0:       a=arr.index(x)       if c==1:           return [a,a]       if c>1:           return [a,a+c-1]   return l1
 
0
subhambhttachariya032 days ago
JAVA CODE : 
 
ArrayList<Long> find(long arr[], int n, int x)   {       // code here       HashMap<Integer, Long> ans = new HashMap<>();       ArrayList<Long> al = new ArrayList<>();       ArrayList<Long> res = new ArrayList<>();              for(int i = 0; i < n; i++) {           if(arr[i] == x) {               ans.put(i, arr[i]);       // Store index as an Key           }       }              if(ans.size() >= 1) {           for(java.util.Map.Entry<Integer, Long> map : ans.entrySet()) {               al.add((long)map.getKey()); // Add all the key in arrayList           }                  Collections.sort(al);         // Sort the index values                  res.add(al.get(0));           // Store the first value           res.add(al.get(al.size()-1)); // Store the last value           // System.out.println(ans);                      ans.clear();           al.clear();       } else {                         // If the search value is not present then add -1           res.add((long)-1);           res.add((long)-1);       }              return res;
   }
+1
ramesh76909507023 days ago
vector<int> find(int arr[], int n , int x )
{
   // code here
   vector<int> ans;
   int s=0;
   int e=n-1;
   int first=-1;
   int last=-1;
   while(s<=e)
   {
       int mid=s+(e-s)/2;
       if(arr[mid]==x)
       {
           first=mid;
           e=mid-1;
       }
       else if(arr[mid]>x)
       {
           e=mid-1;
       }
       else
       {
           s=mid+1;
       }
   }
   
   s=0;
   e=n-1;
   
   while(s<=e)
   {
       int mid=s+(e-s)/2;
       if(arr[mid]==x)
       {
           last=mid;
           s=mid+1;
       }
       else if(arr[mid]>x)
       {
           e=mid-1;
       }
       else
       {
           s=mid+1;
       }
   }
   ans={first,last};
   return ans;
}
0
mandeepjain004 days ago
Approach
 
Find an element X  by using  Binary Search 
When you find x element save index in element and move end to m-1 
This will help you to search first occurrence (agar uske phle koi element ho skta hai)
 
This way we can find last occurrence change is that instead of moving end to m-1 move start to m+1 
 
 OR you can find last occurrence  iterative too complexity will be almost same (in coments)
 
Code 
//first occurrence 
    int start = 0;
    int end = n-1;
    int StartPos = -1;
    while(start <= end){
        
        int mid = start + (end-start)/2;
        if(arr[mid] == x){
            StartPos = mid;
    //jha element mila h uske phle bhi ho skta hai tou check kro
            end = mid-1;
        }
        else if(arr[mid] < x) start = mid+1;
        else end = mid-1;
    }
    
    if(StartPos < 0) return {-1,-1};
    //last occurance 
   // int i = StartPos;
    //while(arr[i] == x) i++;
    int EndPos = -1;
    start = 0;
    end = n-1;
    while(start <= end){
        
        int mid = start + (end-start)/2;
        if(arr[mid] == x){
            EndPos = mid;
    //jha element mila h uske phle bhi ho skta hai tou check kro
            start = mid+1;
        }
        else if(arr[mid] < x) start = mid+1;
        else end = mid-1;
    }
    return {StartPos, EndPos};
-1
himv1135 days ago
//C++ EASIEST SOLUTION
vector<int> find(int arr[], int n , int x )
{
   // code here
   vector<int>v;
   int count=0;
   for(int i=0;i<n;i++){
       if(arr[i]==x){
           v.push_back(i);
           while(arr[i]==x){
               count++;
               i++;
           }
           break;
       }
   }
   if(v.size()==0){
       v.push_back(-1);
       v.push_back(-1);
   }
   else{
   v.push_back(v[0]+count-1);}
   return v;
}
+2
lekoloritse5 days ago
SIMPLE JAVA CODE USING BINARY SEARCH
class GFG
{
    ArrayList<Long> find(long arr[], int n, int x)
    {
        ArrayList<Long> list = new ArrayList<>();
        list.add(first(arr,n,x));
        list.add(last(arr,n,x));
        return list;
    }
    public static long first(long[] arr, int n, int x){
        int start=0;
        int end= n-1;
        long res=-1;
        while(start<=end){
            int mid = start + (end -start)/2;
            if(x==arr[mid]){
                res=mid;
                end=mid-1;
            }
            else if(x<arr[mid]){
                end=mid-1;
            }
            else{
                start=mid+1;
            }
        }
        return res;
    }
    public static long last(long[] arr, int n ,int x){
        int start=0;
        int end= n-1;
        long res=-1;
        while(start<=end){
            int mid = start + (end -start)/2;
            if(x==arr[mid]){
                res=mid;
                start=mid+1;
            }
            else if(x<arr[mid]){
                end=mid-1;
            }
            else{
                start=mid+1;
            }
        }
        return res;
    }
}
0
nitesh800
This comment was deleted.
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.