algoadvance

Leetcode 1832. Check if the Sentence Is Pangram

Problem Statement

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, return true if sentence is a pangram, or false otherwise.

Example

Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: The sentence contains at least one of every letter of the English alphabet.

Input: sentence = "leetcode"
Output: false

Clarifying Questions

  1. Input constraints: What is the maximum length of the input sentence?
    • Assumption: The maximum length of sentence can be large, but for practical purposes, we might assume up to around 10^4 characters since it’s feasible to handle such strings in memory.
  2. Character constraints: Are there any non-ASCII punctuation or special characters?
    • No, the sentence contains only lowercase English letters.

Strategy

We can solve this problem using a set to track which characters we have encountered in the sentence. The idea is to:

  1. Create a set to store each unique character encountered in the string.
  2. Iterate through each character in the input sentence.
  3. Add each character to the set.
  4. After processing the sentence, if the set contains 26 unique characters, return true; otherwise, return false.

This approach works because the set automatically handles duplicates and ensures that only unique characters are counted.

Code

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public boolean checkIfPangram(String sentence) {
        // A set to keep track of unique characters
        Set<Character> uniqueCharacters = new HashSet<>();

        // Iterate over each character in the sentence
        for (char c : sentence.toCharArray()) {
            uniqueCharacters.add(c);
        }

        // There are 26 letters in the English alphabet
        return uniqueCharacters.size() == 26;
    }

    public static void main(String[] args) {
        String sentence1 = "thequickbrownfoxjumpsoverthelazydog";
        String sentence2 = "leetcode";

        Solution sol = new Solution();

        System.out.println(sol.checkIfPangram(sentence1)); // Output: true
        System.out.println(sol.checkIfPangram(sentence2)); // Output: false
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI