1832. Check if the Sentence Is Pangram
Problem Description
A pangram is a sentence that contains every letter of the English alphabet at least once. For example, "The quick brown fox jumps over the lazy dog" is a pangram because it uses all 26 letters from 'a' to 'z'.
Given a string sentence
that contains only lowercase English letters, you need to determine if it's a pangram. Return true
if the sentence contains all 26 letters of the alphabet at least once, and false
otherwise.
The solution works by converting the string to a set, which automatically removes duplicate characters. Since there are exactly 26 letters in the English alphabet, if the set has 26 unique characters, then the sentence must contain every letter from 'a' to 'z', making it a pangram. The check len(set(sentence)) == 26
elegantly verifies this condition - if there are fewer than 26 unique characters, some letters are missing; if there are exactly 26, all letters are present (since the input only contains lowercase English letters).
Intuition
The key insight is recognizing what we're really checking for - we need to verify that all 26 letters of the alphabet appear in the string. We don't care about how many times each letter appears, just whether it appears at least once.
This naturally leads us to think about unique elements. When we have duplicates that we want to ignore, a set data structure is perfect because it automatically keeps only unique values.
Since the problem guarantees the input contains only lowercase English letters, we know there are no special characters or uppercase letters to worry about. This means if we collect all unique characters from the string and count them, the only way to get exactly 26 unique characters is if every letter from 'a' to 'z' is present.
The elegance of this approach is that we don't need to explicitly check for each letter individually (like checking if 'a' exists, if 'b' exists, etc.). Instead, we can leverage the mathematical property that there are exactly 26 letters in the English alphabet. By converting the string to a set and checking if its size equals 26, we implicitly verify that all letters are present in one simple operation: len(set(sentence)) == 26
.
This transforms what could be a complex checking problem into a simple counting problem - if we have 26 unique lowercase letters, we must have the complete alphabet.
Solution Approach
The solution uses a hash table (set) approach to track unique characters in the string.
Step-by-step implementation:
-
Convert string to set: Use Python's built-in
set()
function on the input stringsentence
. This operation iterates through each character in the string and adds it to a set data structure. Since sets only store unique elements, any duplicate letters are automatically ignored. -
Count unique characters: Apply the
len()
function to get the size of the set, which represents the count of unique characters in the sentence. -
Check for pangram condition: Compare the count with 26. If the set contains exactly 26 unique characters, and we know the input only contains lowercase English letters, then all letters from 'a' to 'z' must be present.
Why this works:
- The set automatically handles the "at least once" requirement by eliminating duplicates
- Since the input is restricted to lowercase English letters only, having 26 unique characters guarantees we have the complete alphabet
- No need for explicit iteration or individual letter checking
Time Complexity: O(n)
where n
is the length of the sentence, as we need to traverse the entire string once to build the set.
Space Complexity: O(1)
- while we create a set, it can contain at most 26 unique characters regardless of the input size, making the space usage constant.
The beauty of this approach lies in its simplicity - a single line of code return len(set(sentence)) == 26
elegantly solves the entire problem by leveraging the properties of sets and the fixed size of the English alphabet.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with a small example to see how it works.
Example 1: sentence = "thequickbrownfoxjumpsoverthelazydog"
Step 1: Convert string to set
- Original string:
"thequickbrownfoxjumpsoverthelazydog"
- When we apply
set(sentence)
, each character is added to the set:- First 't' is added:
{'t'}
- Then 'h' is added:
{'t', 'h'}
- Then 'e' is added:
{'t', 'h', 'e'}
- Continue this process...
- When we encounter 't' again (from "the"), it's not added since 't' already exists
- When we encounter 'h' again, it's not added since 'h' already exists
- And so on...
- First 't' is added:
- Final set contains:
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
Step 2: Count unique characters
len(set(sentence))
= 26
Step 3: Check pangram condition
- Is 26 == 26? Yes!
- Return
true
- this is a pangram
Example 2: sentence = "abc"
Step 1: Convert string to set
- Original string:
"abc"
- Apply
set(sentence)
:{'a', 'b', 'c'}
Step 2: Count unique characters
len(set(sentence))
= 3
Step 3: Check pangram condition
- Is 3 == 26? No!
- Return
false
- this is not a pangram (missing 23 letters)
The key insight demonstrated here is that the set automatically handles duplicates for us. In Example 1, even though letters like 't', 'h', 'e', 'o' appear multiple times in the sentence, they only count once in our set. This makes checking for "at least once" trivial - we just need to verify we have all 26 letters present.
Solution Implementation
1class Solution:
2 def checkIfPangram(self, sentence: str) -> bool:
3 """
4 Check if the given sentence is a pangram.
5 A pangram is a sentence containing every letter of the alphabet at least once.
6
7 Args:
8 sentence: A string containing lowercase English letters
9
10 Returns:
11 True if the sentence contains all 26 letters, False otherwise
12 """
13 # Convert string to set to get unique characters
14 # Check if the number of unique characters equals 26 (a-z)
15 return len(set(sentence)) == 26
16
1class Solution {
2 /**
3 * Checks if the given sentence is a pangram.
4 * A pangram is a sentence containing every letter of the alphabet at least once.
5 *
6 * @param sentence the input string to check (assumed to contain only lowercase letters)
7 * @return true if the sentence is a pangram, false otherwise
8 */
9 public boolean checkIfPangram(String sentence) {
10 // Create a boolean array to track which letters have been seen
11 // Index 0 represents 'a', index 1 represents 'b', and so on
12 boolean[] lettersSeen = new boolean[26];
13
14 // Iterate through each character in the sentence
15 for (int i = 0; i < sentence.length(); i++) {
16 // Mark the corresponding letter as seen
17 // Convert character to array index by subtracting 'a'
18 int letterIndex = sentence.charAt(i) - 'a';
19 lettersSeen[letterIndex] = true;
20 }
21
22 // Check if all 26 letters have been seen
23 for (boolean isLetterSeen : lettersSeen) {
24 if (!isLetterSeen) {
25 // If any letter is missing, it's not a pangram
26 return false;
27 }
28 }
29
30 // All letters are present, it's a pangram
31 return true;
32 }
33}
34
1class Solution {
2public:
3 bool checkIfPangram(string sentence) {
4 // Array to track which letters have been seen (0 = not seen, 1 = seen)
5 // Index 0 represents 'a', index 1 represents 'b', and so on
6 int letterSeen[26] = {0};
7
8 // Iterate through each character in the sentence
9 // Mark the corresponding letter as seen in the array
10 for (char& ch : sentence) {
11 letterSeen[ch - 'a'] = 1;
12 }
13
14 // Check if all 26 letters have been seen
15 for (int& seen : letterSeen) {
16 if (!seen) {
17 return false; // Missing at least one letter
18 }
19 }
20
21 // All letters from 'a' to 'z' are present
22 return true;
23 }
24};
25
1/**
2 * Checks if a given sentence is a pangram (contains all 26 letters of the alphabet)
3 * @param sentence - The input string to check
4 * @returns true if the sentence contains all letters a-z, false otherwise
5 */
6function checkIfPangram(sentence: string): boolean {
7 // Create a boolean array to track which letters have been seen
8 // Index 0 represents 'a', index 1 represents 'b', etc.
9 const lettersSeen: boolean[] = new Array(26).fill(false);
10
11 // Iterate through each character in the sentence
12 for (const character of sentence) {
13 // Calculate the index for this letter (0 for 'a', 1 for 'b', etc.)
14 // and mark it as seen in our tracking array
15 const letterIndex: number = character.charCodeAt(0) - 'a'.charCodeAt(0);
16 lettersSeen[letterIndex] = true;
17 }
18
19 // Check if all 26 letters have been seen
20 // Returns true only if every element in the array is true
21 return lettersSeen.every((isLetterPresent: boolean) => isLetterPresent);
22}
23
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the string sentence
. This is because the set()
function needs to iterate through each character in the sentence exactly once to build the set of unique characters.
The space complexity is O(C)
, where C
is the size of the character set. In this problem, C = 26
since we're checking for pangrams which contain all 26 letters of the English alphabet. The set created will store at most 26 unique characters (assuming only lowercase English letters), making the space complexity O(26)
which simplifies to O(1)
constant space.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Assuming Mixed Case Input
The most common mistake is not accounting for uppercase letters or mixed case input. The current solution only works correctly when the input contains exclusively lowercase letters.
Pitfall Example:
sentence = "The Quick Brown Fox Jumps Over The Lazy Dog"
return len(set(sentence)) == 26 # Returns False (incorrectly)
# The set would contain both 'T' and 't' as separate characters
Solution: Convert the string to lowercase before creating the set:
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence.lower())) == 26
2. Not Handling Non-Alphabetic Characters
If the input contains spaces, numbers, or special characters, the solution would count these as unique characters, potentially giving incorrect results.
Pitfall Example:
sentence = "abc def ghi jkl mno pqr stu vwx yz" # Contains spaces
return len(set(sentence)) == 26 # Returns False due to space being counted
Solution: Filter out non-alphabetic characters:
def checkIfPangram(self, sentence: str) -> bool:
# Method 1: Using filter with isalpha()
return len(set(filter(str.isalpha, sentence.lower()))) == 26
# Method 2: Using set comprehension
return len({c for c in sentence.lower() if c.isalpha()}) == 26
3. Alternative Approach Using All Letters Check
While not a pitfall per se, there's an alternative approach that explicitly checks for each letter, which can be more readable and doesn't rely on the assumption that input contains only valid characters:
def checkIfPangram(self, sentence: str) -> bool:
# Create a set of all lowercase letters a-z
alphabet = set('abcdefghijklmnopqrstuvwxyz')
# Check if all letters exist in the sentence
return alphabet.issubset(set(sentence.lower()))
# Or more concisely:
return set('abcdefghijklmnopqrstuvwxyz') <= set(sentence.lower())
This approach is more robust as it explicitly verifies the presence of each required letter rather than relying on counting.
Given a sorted array of integers and an integer called target, find the element that
equals to the target and return its index. Select the correct code that fills the
___
in the given code snippet.
1def binary_search(arr, target):
2 left, right = 0, len(arr) - 1
3 while left ___ right:
4 mid = (left + right) // 2
5 if arr[mid] == target:
6 return mid
7 if arr[mid] < target:
8 ___ = mid + 1
9 else:
10 ___ = mid - 1
11 return -1
12
1public static int binarySearch(int[] arr, int target) {
2 int left = 0;
3 int right = arr.length - 1;
4
5 while (left ___ right) {
6 int mid = left + (right - left) / 2;
7 if (arr[mid] == target) return mid;
8 if (arr[mid] < target) {
9 ___ = mid + 1;
10 } else {
11 ___ = mid - 1;
12 }
13 }
14 return -1;
15}
16
1function binarySearch(arr, target) {
2 let left = 0;
3 let right = arr.length - 1;
4
5 while (left ___ right) {
6 let mid = left + Math.trunc((right - left) / 2);
7 if (arr[mid] == target) return mid;
8 if (arr[mid] < target) {
9 ___ = mid + 1;
10 } else {
11 ___ = mid - 1;
12 }
13 }
14 return -1;
15}
16
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!