Search code examples
javaarraysrecursionbinary-search

My solution throwing exception with corner cases?


Given an array in which I have to print first index of repeating given element in array through recursion and binary search but with corner case like for array[0] it is throwing exception ArrayIsOutOfBound. And this is happening in every solution even if I have to find last index of repeating given element in array through recursion and binary search for element at array.length -

  1. Why? And how to get rid of this?

To find last index-

Input:

int[] array = {5, 10, 10, 10, 10, 20, 20} 

int X = 20;

Output should be:

6

My output is throwing exception.

My solution is:

public static void main(String[] args) {

    int[] arr = {5, 10, 10, 10, 10, 20, 20};
    int X = 20;
    System.out.println(lastOcc(arr, 0, arr.length - 1, X));
}
public static int lastOcc(int[] arr, int low, int high, int X) {
    if(low > high){
        return -1;
    }
    int mid = low + high / 2;

    if(arr[mid] == X) {
        if (mid == arr.length - 1 || arr[mid] != arr[mid + 1]) {
            return mid;
        } else
            return lastOcc(arr,mid + 1, high, X);
    } else if (arr[mid] > X) {
        return lastOcc(arr, low, mid - 1, X);
    } else
        return lastOcc(arr, mid + 1, high, X);
}

To find first index-

Input:

int[] arr = {10, 20, 20, 30, 40, 50, 60}

int X = 10;

Output should be:

0

But it is throwing exception

My Solution is:

public static void main(String[] args) {    
        int[] arr = {10, 20, 20, 30, 40, 50, 60};    
        int x = 10;
        System.out.println(firstOcc(arr, 0, arr.length - 1, x));    
    }

 public static int firstOcc(int[] arr, int low, int high, int x){

        if(low > high){    
            return -1;    
        }

        int mid = low + high / 2;

        if(arr[mid] == x){    
            if(arr[mid  - 1] != arr[mid] || mid == 0){    
                return mid;    
            } else
               return firstOcc(arr, low, mid - 1, x);
        }

        if(x > arr[mid]){    
            return firstOcc(arr, mid + 1, high, x);    
        } else    
            return firstOcc(arr, low, mid - 1, x);    
    }

Solution

  • Well for this instance you only need to add brackets

    int mid = (low + high) / 2;
    

    as

    Division is performing prior to addition

    And also In "FirstOccurrence" change

     if(arr[mid  - 1] != arr[mid] || mid == 0)  to
    
     if(mid == 0 || arr[mid  - 1] != arr[mid] )
    

    as this will omit exception for X=5