In this Pangrams Hacker Rank Problem, A pangram is a string that contains every letter of the alphabet. Given a sentence determine whether it is a pangram in the English alphabet. Ignore case. Return either pangram or not pangram as appropriate.
Example
s = ‘The quick brown fox jumps over lazy dog’
The string contains all letters in the English alphabet, so return pangram.
Pangrams Hacker Rank Solution:
This algorithm checks whether a given sentence is a pangram or not. A pangram is a sentence that contains every letter of the alphabet. The function takes a string s
as an input and converts it to lowercase to ignore the case sensitivity. Then the function uses an array alphabet
to keep track of the count of each letter in the sentence. The array alphabet
is initialized with 0’s and its size is 26 as it needs to hold counts for each letter in the alphabet.
The function iterates through each character of the sentence if the character is a letter of the alphabet (using isalpha()
in C or isLetter()
in Java or ctype_alpha()
in PHP) we increment the count of the corresponding letter in the alphabet array by 1. Once the iteration is done, the function iterates through the alphabet array again, and checks if the count of any letter is 0, if yes means that the letter is not present in the sentence, so it’s not a pangram so return,s not pangram, otherwise, all letters are present so it’s a pangram and returns ‘pangram’.
Problem solution in Python programming:
def pangrams(s): s = s.lower() letters = set([l.lower() for l in s if l.isalpha()]) count = 0 for l in letters: if s.count(l) > 0: count += 1 if count == 26: return 'pangram' else: return 'not pangram'
Problem solution in C++ programming:
string pangrams(string s) { set<char> alphaSet{}; for(const auto&c : s) if(isalpha(c)) alphaSet.insert(tolower(c)); return alphaSet.size() == 'z'-'a'+1 ? "pangram" : "not pangram"; }
Problem solution in JavaScript programming:
function pangrams(s) { let arr = Array(26).fill(0) let op = ''; let stringArr = s.toLowerCase().split(' ').join('').split(''); for (let string of stringArr) { let code = string.charCodeAt(0) - 97; arr[code] += 1; } if (arr.includes(0)) { op = 'not pangram' } else { op = 'pangram'; } return op; }
Problem solution in Java programming:
public static String pangrams(String s) { s = s.toLowerCase().replaceAll(" ", ""); HashSet<Character> set = new HashSet<>(); for(int i=0; i<s.length(); i++){ set.add(s.charAt(i)); } if(set.size()==26){ return "pangram"; } else { return "not pangram"; } }
Leave a Reply