VOOZH about

URL: https://www.geeksforgeeks.org/dsa/balance-consonant-and-vowels-ratio/

⇱ Balance Consonant and Vowels Ratio - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Balance Consonant and Vowels Ratio

Last Updated : 11 Jul, 2025

You are given an array of strings arr[], where each string contains only lowercase English letters. Count the number of contiguous subarrays (i.e., one or more consecutive strings from arr[]) whose concatenation forms a balanced string.

Note: A string is considered balanced if it contains an equal number of vowels and consonants.

Examples:

Input: arr[] = ["aeio", "aa", "bc", "ot", "cdbd"]
Output: 4
Explanation: arr[0...4], arr[1...2], arr[1...3], arr[3...3] are the balanced substrings with equal consonants and vowels.

Input: arr[] = ["ab", "be"]
Output: 3
Explanation: arr[0..0], arr[0..1], arr[1..1] are the balanced substrings with equal consonants and vowels.

Input: arr[] = ["tz", "gfg", "ae"]
Output: 0
Explanation: There is no such balanced substring present in arr[] with equal consonants and vowels.

[Naive Approach] Generate all possible subarrays

Try all possible contiguous subarrays of arr[], concatenate the strings within each subarray, and count the number of vowels and consonants in the resulting string. If the counts are equal, the string is considered balanced, and we increment our result.


Output
4

Time Complexity: O(n² * l), where n is the number of strings and l is the total length of all strings combined, because for each of the O(n²) subarrays, all characters are concatenated and scanned.
Space Complexity: O(l), where l is the length of the longest possible concatenated string, used by the temporary string s.

[Expected Approach] Using Hash Map

Assign each string a net score: +1 for every vowel and -1 for every consonant. Compute the prefix sum of these scores across the array. If the same prefix sum appears more than once, the subarray between those indices has equal vowels and consonants. Use a hash map to count the frequency of each prefix sum during traversal. Add the frequency of the current prefix sum to the result before updating it.

Time Complexity: O(n * l), where n is the number of strings and l is the average length of each string, since each character in all strings is processed once.
Space Complexity: O(n), due to the prefix sum frequency map which can store up to n unique prefix values.

Comment
Article Tags:
Article Tags: