educative.io

Educative

In the findIndexHigh

Hello,
I am new to DSA problems and I need help!

In the findIndexHigh function.

if (high === -1){
return high
}. // -------------> What is the reason for this statement ?

// high < nums.length —> is this checking if it is in bound of the original array?
if (high < nums.length && nums[high] === target) {
return high;
}

Thank you all!

Dear @Ki_Woo_Kim ,
These are some additional checks.

if (high === -1){ return high }.
The above code checks the conditions where high value reaches -1. For example, if the array is empty, high will become -1. Also, if the target value is not there in the array and all the present values are greater than our target value. In this case, high will become -1 as well.
Our function will return -1 in all such cases.

Keep in mind that -1 means that we couldn’t find the target value in our array.

In the second point, yes you’re right. That is the boundary check. Value of high must be less than the size of our array. For Example, if the size of our array is 6, high should always be less than 6.

If we skip both these checks, our code will work fine as well because we have written return -1 at the end. Whenever our code fails to find the target, it always returns -1. The above checks are some additional checks to learn all the failure cases and to stay more secure.