Check if the Sentence Is Pangram — Problem & Solution
Check if the Sentence Is Pangram solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Check if the Sentence Is Pangram is an easy coding problem on strings and hash table, asked in Amazon, TCS and Infosys interviews.
- Difficulty: Easy
- Topics: Strings, Hash Table
- Asked at: Amazon, TCS, Infosys
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A pangram is a sentence that uses every letter of the English alphabet at least once.
Given a string sentence of lowercase English letters, return true if it is a pangram.
Example 1
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Example 2
Input: sentence = "leetcode"
Output: false
Example 3
Input: sentence = "abcdefghijklmnopqrstuvwxyz"
Output: true
Constraints
1 <= sentence.length <= 40sentence consists of lowercase English letters.
Hints for Check if the Sentence Is Pangram
Hint 1
Collect the distinct letters and check whether there are 26 of them.
Hint 2
A 26-bit mask works too: set bit
ch - 'a'and compare the mask against(1 << 26) - 1.Hint 3
Any sentence shorter than 26 characters can be rejected immediately.
How to solve Check if the Sentence Is Pangram
Collect the distinct letters and check whether all 26 are present.
Approach
- Build a set of the characters.
- Return whether its size is 26.
Why it works
The sentence is all lowercase letters, so the set can hold at most 26 values and reaches 26 exactly when every letter appears.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- A 26-bit mask compared against
(1 << 26) - 1avoids the set. - Anything shorter than 26 characters can be rejected without looking.
Reference solution
Python
def checkIfPangram(sentence: str) -> bool:
return len(set(sentence)) == 26Java
public static boolean checkIfPangram(String sentence) {
int mask = 0;
for (int i = 0; i < sentence.length(); i++) {
mask |= 1 << (sentence.charAt(i) - 'a');
}
return mask == (1 << 26) - 1;
}C++
bool checkIfPangram(string sentence) {
int mask = 0;
for (char c : sentence) mask |= 1 << (c - 'a');
return mask == (1 << 26) - 1;
}JavaScript
var checkIfPangram = function(sentence) {
const seen = new Set();
for (let i = 0; i < sentence.length; i++) seen.add(sentence[i]);
return seen.size === 26;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings · Hashing: Hash Maps and Hash Sets