Missing characters to make string pangram in Java

In this tutorial, we will find what are the missing characters in a given string to make it a pangram in Java.

What is a pangram?

A pangram is a sentence that contains all the alphabets at least once. For example,

“The quick brown fox jumps over the lazy dog”. This sentence contains all the alphabets from ‘a’ to ‘z’.

Input Format:

The first line of the input is a string most probably a sentence.

Output Format:

Print the alphabets that are missing in that string to make it a pangram.

Sample Input:

the quick brown fox jumps over the lazy

Sample Output:

dg

Explanation: The given string contains all the alphabets except ‘d’ and ‘g’. If those two alphabets are included then it would be a pangram. So, the output is “dg”.

Approach: To solve this problem we use a simple count array of size 26 which contains the frequency of all alphabets from ‘a’ to ‘z’. Based on the occurrence of the alphabet in the string, we increment the count of the corresponding alphabet. After this, we check the frequency of alphabets of count array then if the frequency is ‘zero’ that means that the alphabet is not present in the entire given string. So, we append it to a new String and print it.

Find missing characters to make string pangram in Java

import java.util.*;
import java.lang.*;
class codespeedy
{
  public static void main(String[] args) {
      String str="The quick brown fox jumps over the lazy";
      char s[]=str.toCharArray();
      int c[]=new int[26];
      for(int i=0;i<s.length;i++){
          if(s[i]!=' '){
              c[s[i]-'a']++;
          }
      }
      String s2="";
      for(int i=0;i<26;i++){
          if(c[i]==0){
              s2=s2+(char)(i+'a');
          }
      }
      System.out.println(s2);
  }
}

Output:

dg

line 7-13: We convert the given string to a character array using [ toCharArray() ] and declare a count array for 26 alphabets. Using for loop increment the count array for each occurrence of a character.

line 14-20: Declare a new empty string and append each character which has count zero. Print the new string which contains missing characters to make the given string pangram.

Time Complexity: O(n)

Also read:

One response to “Missing characters to make string pangram in Java”

  1. Shekhar says:

    It will throw arrayindexoutofbounds exception we need to convert it into lowercase and then we can find missing letters.

Leave a Reply

Your email address will not be published. Required fields are marked *