Taro Logo

Check if the Sentence Is Pangram

Easy
Amazon logo
Amazon
2 views
Topics:
Strings

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?

Solution


Naive Solution

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

Optimal Solution

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

Edge Cases:

  • Empty String: An empty string is not a pangram.
  • String with non-alphabetic characters: The problem statement specifies that the input string will contain only lowercase English letters, so we don't need to handle the edge case of non-alphabetic characters.
  • Very long string: While the constraints limit the length of the input string, the solutions should handle potentially longer strings efficiently.

Time and Space Complexity:

Naive Solution:

  • Time Complexity: O(N * M), where N is the length of the alphabet (26) and M is the length of the sentence. This is because, for each letter in the alphabet, we iterate through the sentence to check if it's present.
  • Space Complexity: O(1), as we use a fixed amount of space to store the alphabet.

Optimal Solution:

  • Time Complexity: O(M), where M is the length of the sentence. This is because we iterate through the sentence once to add each character to the set.
  • Space Complexity: O(1), which is more accurately O(min(M, 26)), because in the worst case we may need to store all 26 unique characters in the set.