Skip to content

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.


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

["a","b","c","d","f"] -> "e" ["O","Q","R","S"] -> "P"
Code language: JavaScript (javascript)

(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[]; for(char letter : array) { if(letter != expectableLetter) break; expectableLetter++; } return expectableLetter; } }
Code language: Java (java)

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 '?'; } }
Code language: Java (java)

Option 3:

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

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' })); } }
Code language: Java (java)

See also  Calculate Miles per Gallon to Kilometers per Litre in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x