![]() |
VOOZH | about |
Write a program to count the number of consonants in a given word. Consonants are the letters of the English alphabet excluding vowels ('a', 'e', 'i', 'o', 'u').
Examples:
Input: "programming"
Output: 8
Explanation: The eight consonants are: 'p', 'r', 'g', 'r', 'm', 'm', 'n', 'g')Input: "hello"
Output: 3
Explanation: There are three consonants: 'h', 'l', 'l'
Approach: To solve the problem, follow the below idea:
The problem can be solved by iterating through the entire word character by character and for each character, check if the character is a vowel. If the character is 'a' or 'e' or 'i' or 'o' or 'u', then it is a vowel otherwise it is a consonant. If the character is a consonant, increment the answer by 1.
Step-by-step algorithm:
Below is the implementation of the approach:
Number of consonants: 8
Time Complexity: O(N) where N is the length of the word.
Auxiliary Space: O(1) (constant space is used)