educative.io

Educative

Is start % n required if we are checking edge case in the if at the beginning?

public static char searchNextLetter(char[] letters, char key) {

    int n = letters.length;

    if (key < letters[0] || key > letters[n - 1])

      return letters[0];

    int start = 0, end = n - 1;

    while (start <= end) {

      int mid = start + (end - start) / 2;

      if (key < letters[mid]) {

        end = mid - 1;

      } else { //if (key >= letters[mid]) {

        start = mid + 1;

      }

    }

    // since the loop is running until 'start <= end', so at the end of the while loop, 'start == end+1'

    return letters[start % n];

  }
1 Like

It is not, the return letters[start] at the end is enough due to the fact it is not possible to reach that line without passing the beginning edge case

Actually it is required for the case where key === end index value
In that case you will return the start of the array.
Example
[a, c, f, h] key = h
return ‘a’ with input[start % n]