DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

Check if the Sentence Is Pangram | LeetCode | Java

In this article, we will focus on 3 different approaches to solve the problem.

Approach 1 : Using HashSet

In this, we store the entire sentence in a HashSet. The catch here is that the set will not contain duplicate characters. So, we add the elements to the set and see if the set size is equal to the 26 letters.

class Solution {
    public boolean checkIfPangram(String sentence) {

        Set<Character> set = new HashSet<>();

        for(char ch : sentence.toCharArray()){
            set.add(ch);
        }

        return set.size()==26;
    }
}
Enter fullscreen mode Exit fullscreen mode

Approach 2 : Using Frequency Array

Here, we are going to store the entire sentence in a frequency array of size 26. We will calculate the occurrence of every element of the alphabet and later run through the frequency array to check if any character is not present.

class Solution {
    public boolean checkIfPangram(String sentence) {

        boolean freq[] = new boolean[26];

        for(char ch : sentence.toCharArray()){
            freq[ch-'a'] = true;
        }

        for(boolean val : freq){
            if(val==false)
                return false;
        }

        return true;
    }
}

Enter fullscreen mode Exit fullscreen mode

Approach 3 : Using Built-in function

indexOf() method returns the index within the string of the first occurrence of the specified character or -1, if the character does not occur.

class Solution {
    public boolean checkIfPangram(String sentence) {

        for(int i=0; i<26; i++){
            char ch = (char)(i+'a');

            if(sentence.indexOf(ch)==-1)
                return false;
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)