Find the Missing Letter Using Java


The challenge

Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.

You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.

Example:

[‘a’,‘b’,‘c’,’d’,‘f’] -> ‘e’ [‘O’,‘Q’,‘R’,‘S’] -> ‘P’

["a","b","c","d","f"] -> "e"
["O","Q","R","S"] -> "P"

(Use the English alphabet with 26 letters!)

The solution in Java code

Option 1:

public class Solution {
  public static char findMissingLetter(char[] array) {
    char expectableLetter = array[0];
    for(char letter : array) {
      if(letter != expectableLetter) break;
      expectableLetter++;
    }
    return expectableLetter;
  }
}

Option 2:

public class Solution {

  public static char findMissingLetter(char[] array) {
    for (int i=1; i<array.length; i++) {
      if (array[i]-array[i-1]!=1) return (char)(array[i]-1);
    }
    return '?';
  }
  
}

Option 3:

import java.util.stream.IntStream;

public class Solution {

  public static char findMissingLetter(final char[] array) {
    return IntStream.range(0, array.length - 1)
        .parallel()
        .filter(i -> array[i + 1] != array[i] + 1)
        .mapToObj(i -> (char) (array[i] + 1))
        .findAny().orElseThrow(IllegalArgumentException::new);
  }
} 

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void exampleTests() {
        assertEquals('e', Solution.findMissingLetter(new char[] { 'a','b','c','d','f' }));
        assertEquals('P', Solution.findMissingLetter(new char[] { 'O','Q','R','S' }));
    }
}