Site icon Study Algorithms

Pangrams

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:-

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.

Exit mobile version