A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence
containing only lowercase English letters, determine if sentence
is a pangram.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = "leetcode"
Output: false
Constraints:
1 <= sentence.length <= 1000
sentence
consists of lowercase English letters.Can you implement a function to determine if a given string is a pangram? How would you optimize your approach for efficiency?
A brute force solution would involve iterating through the input string sentence
and checking for the presence of each letter of the alphabet. We can maintain a boolean array or a set to keep track of the letters that have been found. If, after iterating through the entire sentence, all letters of the alphabet are marked as present, then the sentence is a pangram.
Code (Python):
def is_pangram_naive(sentence):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in sentence:
return False
return True
A more efficient solution uses a set to keep track of the unique characters found in the sentence. By adding each character in the sentence to the set, we can avoid redundant checks. If the size of the set is equal to 26 after iterating through the sentence, then it is a pangram.
Code (Python):
def is_pangram_optimal(sentence):
return len(set(sentence)) == 26
Naive Solution:
Optimal Solution: