Home Strings Pangrams

Pangrams

by nikoo28
0 comments 2 minutes read

Question: Given a string, identify if it is a pangram.


Input:
The quick brown fox jumps over the lazy little dog.
Output: pangram

To start with the problem statement we must first understand what is a pangram. A pangram is a string that contains all the characters in the English alphabet at-least once. This means that the string ‘the quick brown fox jumps over the lazy little dog’ will cover each of the letter from ‘a-z’.

So how to identify if a string is a pangram?
You need to keep a check on the occurrence of each of the character present in the string. For the simplicity of our case let us assume that the string has all valid characters which are lowercase. JAVA gives you a feature of a HashSet that only allows one entry of a character.

So our algorithm would be:-

  • Declare an empty hashset.
  • Iterate over the string and insert each character in the hashset.
  • Once the string has been traversed, check the size of the hashset. If it is equal to 26, that means we have covered each of the character in English alphabet.
  • If the size of hashset is less than 26, it means that the string is not a pangram

Take a look at the source code.

public class Pangrams {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        s = s.toLowerCase();

        // Declare a hashset
        HashSet<Integer> h = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ' ') {

                // Add characters in the hashset.
                int put = (int) s.charAt(i);
                h.add(put);
            }
        }
        if (h.size() == 26)
            System.out.println("pangram");
        else
            System.out.println("not pangram");
    }
}
Code language: Java (java)

A working implementation of the code can be found here.

This problem can also be found at HACKERRANK.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More