Sample Problem: Panagram Checking in Java

 Problem: The problem is to check whether a given sentence is a pangram or not. A pangram is a sentence that contains all the 26 English alphabets.

Examples: Input: str = "The quick brown fox jumps over the lazy dog” Output: The sentence is a pangram because it contains all 26 letters of the English alphabet.

Input: str = "abcdefghijklmnopqrstuvwxy" Output: The sentence is not a pangram because it does not contain the letter 'z'.

Approach: To check whether a sentence is a pangram or not, we need to create an empty array of size 26 corresponding to all the letters of the English alphabet. This array will be used to check whether all the alphabets are present in the given sentence or not. We iterate through all the characters of our sentence, and whenever we see a character, we mark it in the array by incrementing the place value. Lowercase and uppercase letters are considered the same. So ‘A’ and ‘a’ are marked in index 0, and similarly, ‘Z’ and ‘z’ are marked in index 25. After iterating through all the characters, we check whether all the characters are marked or not. If not, then the sentence is not a pangram, and we return false, else we return true.

Implementation:

Here's the Java code for implementing the above approach:

import java.util.*;

class PangramChecker {

typescript
static boolean isPangram(String sentence) { int n = sentence.length(); if(n < 26) return false; boolean visited[] = new boolean[26]; for(int i=0; i<n; i++) { char x = sentence.charAt(i); if(x >= 'a' && x <='z') { visited[x-'a'] = true; } if(x >= 'A' && x <='Z') { visited[x-'A'] = true; } } for(int i =0; i<26; i++) { if(visited[i] == false) return false; } return true; } public static void main(String args[]) { String sentence = "The quick brown fox jumps over the lazy dog"; if(isPangram(sentence)) System.out.println(sentence + " is a pangram."); else System.out.println(sentence + " is not a pangram."); }

}

Output: The quick brown fox jumps over the lazy dog is a pangram.

Time Complexity: Since only a single loop is used to iterate through the sentence to check for pangram, the time complexity would be O(n), where n is the length of the given sentence.

Auxiliary Space: Since only a new array of size 26 is created, it occupies O(26) space, which is constant.

Previous Post Next Post