Firat & Last occurance of an element

PHOTO EMBED

Sun Jan 16 2022 07:18:37 GMT+0000 (Coordinated Universal Time)

Saved by @vaibhav_55 #binarysearch

int firstOccurance(vector<int> &ar,int target){
  int low = 0,high = ar.size()-1,ans = -1;
  while(low<=high){
    int mid = low+(high-low)/2;
    
    if(ar[mid]==target){
      //mid can be our answer but we are not sure so reduce the search space
      ans = mid;
      high = mid-1;//for first occurance go to left
    }
    else if(ar[mid]>target)
      high = mid-1;
    else
      low = mid+1;
  }
  return ans;//if element is not present ans will remain -1,and will be returned as it is.
}

int lastOccurance(vector<int> &ar,int target){
  
  int low = 0,high = ar.size()-1,ans = -1;
  while(low<=high){
    int mid = low+(high-low)/2;
    
    if(ar[mid]==target){
      //mid can be our answer but we are not sure so reduce the search space
      ans = mid;
      low = mid+1; //for lasat occurance go to right
    }
    else if(ar[mid]>target)
      high = mid-1;
    else
      low = mid+1; 
  }
  
  return ans;//if element is not present ans will remain -1,and will be returned as it is.
}
content_copyCOPY