Check Pangram in Java
Problem
A pangram is a sentence that contains every letter of the alphabet at least once.
Given a sentence, determine whether it is a pangram.
Java Program
public class PangramCheck {
public static void main(String[] args) {
String str = "The quick brown fox jumps over the lazy dog";
boolean[] seen = new boolean[26];
for (char c : str.toLowerCase().toCharArray()) {
if (c >= 'a' && c <= 'z') { // only letters count toward the alphabet check
seen[c - 'a'] = true; // mark this letter as seen
}
}
boolean isPangram = true;
for (boolean letterSeen : seen) {
if (!letterSeen) {
isPangram = false;
break; // found a missing letter, no need to check the rest
}
}
System.out.println("Pangram: " + isPangram);
}
}Output
Core Logic
Marking off each letter as it's seen, then checking that all 26 slots got marked, confirms whether every letter appeared.
- 1
str.toLowerCase()normalizes the sentence so uppercase and lowercase letters are treated the same. - 2A
boolean[26]array namedseenhas one slot per letter of the alphabet. - 3For each letter character,
seen[c - 'a'] = truemarks its corresponding slot. - 4A final pass checks whether every slot in
seenistrue— if even one isfalse, that letter never appeared.
"The quick brown fox jumps over the lazy dog", every one of the 26 slots ends up marked true.Key Point: Only letters ('a' through 'z') update seen — spaces and any other characters are simply skipped.
Why: Each character is visited once to mark its letter, and the tracking array has a fixed size of 26 regardless of the sentence's length.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class PangramCheckStream {
public static void main(String[] args) {
String str = "The quick brown fox jumps over the lazy dog";
String lower = str.toLowerCase();
// Every letter a-z must appear somewhere in the lowercased sentence
boolean isPangram = IntStream.rangeClosed('a', 'z')
.allMatch(c -> lower.indexOf(c) != -1);
System.out.println("Pangram: " + isPangram);
}
}
Output
Core Logic
Instead of marking letters as they're found, the check can ask the opposite question directly — does every letter of the alphabet appear somewhere in the sentence?
- 1
IntStream.rangeClosed('a', 'z')generates the character codes for every letter of the alphabet. - 2
.allMatch(c -> lower.indexOf(c) != -1)checks that each letter appears at least once in the lowercased sentence. - 3
allMatch()returnstrueonly if every single letter is found, and stops at the first missing one.
indexOf() finds a match for every letter from 'a' to 'z', so allMatch() returns true.Key Point: Each of the 26 indexOf() calls scans the sentence again, so this does more total character comparisons than the single-pass array version — a fine trade-off for readability on a sentence-sized input.
Why: Each of the 26 letters triggers its own linear scan via indexOf(), but since the alphabet size is a fixed constant, the total work still scales linearly with the sentence's length.