Check if the Sentence Is Pangram
Problem
Return whether sentence (lowercase) contains every letter of the English alphabet.
sentence = "thequickbrownfoxjumpsoverthelazydog"truedef check_if_pangram(sentence):
mask = 0
for c in sentence:
mask |= 1 << (ord(c) - 97)
return mask == (1 << 26) - 1
function checkIfPangram(sentence) {
let m = 0;
for (const c of sentence) m |= 1 << (c.charCodeAt(0) - 97);
return m === (1 << 26) - 1;
}
class Solution {
public boolean checkIfPangram(String sentence) {
int m = 0;
for (char c : sentence.toCharArray()) m |= 1 << (c - 'a');
return m == (1 << 26) - 1;
}
}
bool checkIfPangram(string sentence) {
int m = 0;
for (char c : sentence) m |= 1 << (c - 'a');
return m == (1 << 26) - 1;
}
Explanation
A pangram uses all 26 letters at least once. The neat trick here is to track which letters we have seen using a single integer as a 26-bit bitmask instead of a set or array.
We start with mask = 0. For each character c we compute its position in the alphabet with ord(c) - 97 (so 'a' is 0, 'b' is 1, and so on) and turn on that bit using mask |= 1 << (ord(c) - 97). Seeing the same letter again just re-sets a bit that is already on, which is harmless.
At the end, every letter present corresponds to one set bit. The sentence is a pangram exactly when all 26 bits are on. The value with bits 0 through 25 set is (1 << 26) - 1, so we simply compare mask to that.
This is fast and uses constant extra space, since one int holds the whole letter set.
Example: for "thequickbrownfoxjumpsoverthelazydog" every letter appears, so the final mask equals (1 << 26) - 1 and the answer is true.