AlgoInsight

DSA problem

Count Vowels and Consonants

EasyStringsPattern: String TraversalbeginnerFree

Given a string s, count the number of vowels and consonants in it. Ignore non-alphabetic characters.

Iterate through each character. If it is a letter, check whether it is a vowel (a, e, i, o, u - case-insensitive) or a consonant, and maintain two counters. This teaches character classification - checking whether a character belongs to a specific set. The pattern extends to validating input (is this a digit? whitespace? a special character?), parsing, and tokenization. A clean implementation uses a set of vowels for O(1) lookup instead of chaining if-else conditions. The method returns the two counts as a [vowels, consonants] pair.

Examples

Example 1
Input: s = "Hello World"
Output: Vowels: 3, Consonants: 7
Explanation: The vowels are e, o, o (3). The consonants are H, l, l, W, r, l, d (7). The space is ignored.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringcounting

Browse all DSA problems