class Solution:
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence)) == 26
class Solution {
public:
bool checkIfPangram(string sentence) {
vector<bool> seen(26, false);
for (char c : sentence) {
seen[c - 'a'] = true;
}
for (bool b : seen) {
if (!b) return false;
}
return true;
}
};
class Solution {
public boolean checkIfPangram(String sentence) {
boolean[] seen = new boolean[26];
for (char c : sentence.toCharArray()) {
seen[c - 'a'] = true;
}
for (boolean b : seen) {
if (!b) return false;
}
return true;
}
}
var checkIfPangram = function(sentence) {
const seen = new Array(26).fill(false);
for (let c of sentence) {
seen[c.charCodeAt(0) - 'a'.charCodeAt(0)] = true;
}
for (let b of seen) {
if (!b) return false;
}
return true;
};
You are given a string sentence
that consists of only lowercase English letters. Your task is to determine if sentence
is a pangram. A pangram is a sentence that contains every letter of the English alphabet at least once.
true
if sentence
is a pangram, otherwise return false
.sentence
can be up to 1000 characters.'a'
to 'z'
must appear at least once.
The problem asks if a given sentence contains every letter from 'a'
to 'z'
at least once. At first, one might think of checking for every letter by looping through the alphabet and verifying its presence in the string. However, this would be inefficient for long strings.
Instead, we can optimize by tracking which letters we have seen as we iterate through the string. If we have seen all 26 letters, we can immediately return true
. If we reach the end and some letters are missing, we return false
.
This approach avoids unnecessary repeated searches and leverages efficient data structures to keep track of the letters.
Here’s a step-by-step explanation of the efficient solution:
set
(in Python/JavaScript) orsentence
, mark the corresponding letter as seen.
true
immediately for further optimization.
This method is efficient because each letter is processed only once, and lookups and updates to our tracking structure are constant time operations.
Let's consider the input sentence = "thequickbrownfoxjumpsoverthelazydog"
.
true
).'a'
to 'z'
has appeared at least once, we return true
.
If the sentence were "leetcode"
, after processing, not all letters would be present. We would return false
.
O(26 * N)
, where N
is the length of the sentence.O(N)
.O(1)
per operation.O(1)
(since the alphabet size is fixed at 26).O(1)
extra space, since the set or array size is fixed and does not depend on input length.To determine if a sentence is a pangram, we efficiently track the presence of each letter using a set or boolean array. By iterating through the sentence once, we ensure each letter is counted, and we can quickly check if all 26 letters are present. This approach is both time and space efficient, leveraging the fixed size of the English alphabet for a clean and elegant solution.