Python Program to Check if String is Pangram
set('abcdefghijklmnopqrstuvwxyz') is a subset of set(string.lower()), like this: is_pangram = set('abcdefghijklmnopqrstuvwxyz') <= set(input_string.lower()).Examples
How to Think About It
Algorithm
Code
def is_pangram(s: str) -> bool: alphabet = set('abcdefghijklmnopqrstuvwxyz') return alphabet <= set(s.lower()) # Example usage input_string = "The quick brown fox jumps over the lazy dog" print(is_pangram(input_string))
Dry Run
Let's trace the example 'The quick brown fox jumps over the lazy dog' through the code.
Convert string to lowercase
'the quick brown fox jumps over the lazy dog'
Create set of letters in string
{'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'}
Create alphabet set
{'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'}
Check if alphabet is subset of string letters
True
| Step | String Letters Set | Alphabet Set | Is Subset? |
|---|---|---|---|
| 1 | {'a', 'b', 'c', ..., 'z'} | {'a', 'b', 'c', ..., 'z'} | True |
Why This Works
Step 1: Lowercase Conversion
Converting the string to lowercase with s.lower() ensures that letter case does not affect the check.
Step 2: Set Creation
Creating a set of letters from the string removes duplicates and allows easy membership testing.
Step 3: Subset Check
Using alphabet <= set(s.lower()) checks if all alphabet letters are present in the string.
Alternative Approaches
def is_pangram(s: str) -> bool: s = s.lower() return all(chr(c) in s for c in range(ord('a'), ord('z') + 1)) print(is_pangram("The quick brown fox jumps over the lazy dog"))
import string def is_pangram(s: str) -> bool: return not set(string.ascii_lowercase) - set(s.lower()) print(is_pangram("The quick brown fox jumps over the lazy dog"))
Complexity: O(n) time, O(1) space
Time Complexity
The program scans the string once to create a set of letters, which takes O(n) time where n is the string length.
Space Complexity
The extra space is O(1) because the alphabet set size is fixed (26 letters), and the string letter set is at most 26 letters.
Which Approach is Fastest?
Using set operations is generally faster and cleaner than looping with all(), but all() can short-circuit early if letters are missing.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set subset check | O(n) | O(1) | Clean and fast for most cases |
| all() with loop | O(n) | O(1) | Early exit if missing letters |
| Set difference | O(n) | O(1) | Clear logic using set math |