Find the missing letter using Java

1 min read 220 words

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' }));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts