Check if Sentence Is Pangram

Track the letters of the alphabet to decide whether a sentence contains every English letter at least once.

Problem

A pangram is a sentence where every letter of the English alphabet appears at least once.

Given a string sentence, return true if the sentence is a pangram. Return false otherwise.

The sentence may contain uppercase letters, lowercase letters, spaces, digits, or other characters. Only English letters matter.

Examples

Example 1

Input:

sentence = "TheQuickBrownFoxJumpsOverTheLazyDog"

Output:

true

Explanation: every English letter appears at least once, ignoring case.

Example 2

Input:

sentence = "This is not a pangram"

Output:

false

Explanation: at least one English letter is missing.

Nature of the Problem

This is a coverage tracking problem.

We do not care how many times a letter appears. We only care whether each letter appears at least once.

That makes the problem a natural fit for a fixed-size boolean array of length 26, where each position represents one letter from a to z.

Analysis

The alphabet has exactly 26 English letters.

So we can create memory for those letters:

seenLetters = array of 26 false values

Then we scan the sentence one character at a time.

For each character:

  1. Ignore it if it is not an English letter
  2. Convert uppercase letters to lowercase
  3. Convert the lowercase letter into an index from 0 to 25
  4. Mark that index as seen

After scanning the sentence, we check the boolean array.

If every position is true, the sentence is a pangram.

If any position is false, at least one letter is missing.

Pseudocode

function isPangram(sentence) {
    seenLetters = array of 26 false values;

    for each character in sentence {
        if character is not an English letter {
            continue;
        }

        letter = lowercase version of character;
        index = letter - 'a';
        seenLetters[index] = true;
    }

    for each value in seenLetters {
        if value is false {
            return false;
        }
    }

    return true;
}

Step-by-Step Walkthrough

For:

sentence = "abc"

Start with all letters unseen:

seenLetters = [false, false, false, ..., false]

Read a:

index = 0
seenLetters[0] = true

Read b:

index = 1
seenLetters[1] = true

Read c:

index = 2
seenLetters[2] = true

At the end, most letters are still missing, so the answer is:

false

For a full pangram, every index from 0 to 25 would be marked true.

Complexity

Time complexity:

O(n)

We scan the sentence once, where n is the length of the sentence. The final alphabet check always looks at 26 values, which is constant work.

Space complexity:

O(1)

The boolean array always has size 26, regardless of the sentence length.

Key Idea

When a problem asks whether a fixed set of symbols is fully present, think about coverage.

For this problem, the alphabet is the fixed set, and the boolean array records which letters have already appeared.