educative.io

Educative

Understandable exception thrown for solution


Course: https://www.educative.io/courses/coderust-hacking-the-coding-interview
Lesson: Implement Binary Search on a Sorted Array - Coderust: Hacking the Coding Interview

Hey @Prakhar_Shukla!
Here is the correct version of your solution.

class BinarySearch {
static int binarySearch(int[] nums, int target) {
    
    int lo=0;
    int hi= nums.length-1;
    while(lo<=hi){
			
    int mid= lo+((hi-lo)/2);
    if(nums[mid] >= target)
        hi=mid-1;
    else
        lo=mid +1;
	
    if(nums[lo]==target)
        return lo;
    }

   return -1;
 }
}

Hi @Aiman_Fiaz
static int binarySearch(int[] nums, int target) {
int lo = 0;
int hi = nums.length-1;
while(lo < hi) {
int mid = lo + (hi-lo)/2;

		if(nums[mid] >= target)
			hi = mid;
		else
			lo = mid + 1;
	}
	if(nums[lo] == target)
		return lo;
	return -1;
}

This solution is correct, you can check with anything.


Course: Coderust: Hacking the Coding Interview - Learn Interactively
Lesson: Implement Binary Search on a Sorted Array - Coderust: Hacking the Coding Interview

The exception was being thrown in a line out of my code. I changed the code a little bit but it still doesn’t make any sense.


Course: Coderust: Hacking the Coding Interview - Learn Interactively
Lesson: Implement Binary Search on a Sorted Array - Coderust: Hacking the Coding Interview