DEV Community

Alysa
Alysa

Posted on • Updated 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💓
Follow for more 🤝 && Happy Coding🚀👩‍💻

Don't forget to check-out my other socials😍:
Github
Hashnode
Medium
Twitter(X)

Top comments (0)