DSA Day 7/100

DSA Day 7/100

Topic: Searching

Questions Successfully Completed: 1

1) Left Index

Easy

Left Index

Time Complexity : O(logn)

Space Complexity : O(1)

Question
Input: N = 7 arr[] = {10,20,20,20,20,20,20} x = 20 Output: 1 Explanation: 20 is present 5 times, but its leftmost index is 1.
package searching;

public class leftIndex {
    static int leftIndex(int N, int arr[], int X)
   {
        int low=0;
        int high = N-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(arr[mid]<X){
                low = mid+1;
            }
            else if(arr[mid]>X){
                high = mid -1;
            }
            else {
                if(mid==0||arr[mid-1]!=arr[mid]){
                    return mid;
                }
                else{
                    high = mid-1;
                }
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] arr = new int[]{1,1,2,2,3,4,5,5,6,7};
        int x =1;
        System.out.println(leftIndex(arr.length,arr,x));
    }
}

Thank you for reading :)