01. Balancing Consonants and Vowels Ratio
β GFG solution to the Balancing Consonants and Vowels Ratio problem: count balanced substrings with equal vowels and consonants using prefix sum technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array of strings arr[]
, where each arr[i]
consists of lowercase English alphabets. Your task is to find the number of balanced strings in arr[]
which can be formed by concatenating one or more contiguous strings of arr[]
.
A balanced string contains an equal number of vowels and consonants.
π Examples
Example 1
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.
Example 2
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.
Example 3
Input: arr[] = ["tz", "gfg", "ae"]
Output: 0
Explanation: There is no such balanced substring present in arr[]
with equal consonants and vowels.
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$1 \le \text{arr}[i]\text{.size()} \le 10^5$
Total number of lowercase English characters in
arr[]
is lesser than $10^5$
β
My Approach
The optimal approach uses the Prefix Sum technique with a Hash Map to efficiently count balanced substrings:
Prefix Sum + Hash Map
Core Insight:
For a substring to be balanced, the number of vowels must equal the number of consonants.
We can represent this as:
vowels - consonants = 0
Assign
+1
for vowels and-1
for consonants, then find subarrays with sum = 0.
Algorithm Steps:
Initialize a hash map with
{0: 1}
to handle subarrays starting from index 0.For each string in the array, calculate its score (vowels count - consonants count).
Maintain a running sum of scores as we process each string.
If the current sum has been seen before, it means there are subarrays ending at the current position that have a net balance of 0.
Add the frequency of the current sum to the result and increment its count in the hash map.
Key Operations:
Calculate score for each string:
+1
for each vowel,-1
for each consonant.Use prefix sum to track cumulative balance.
Count occurrences of each prefix sum to find balanced subarrays.
Why This Works:
If
prefixSum[j] == prefixSum[i]
forj > i
, then the subarray fromi+1
toj
has sum = 0.This means equal vowels and consonants in that subarray.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n*m), where n is the number of strings and m is the average length of strings. We process each character exactly once to calculate string scores, then perform O(1) hash map operations for each string.
Expected Auxiliary Space Complexity: O(n), where n is the number of strings. In the worst case, we store one entry per string in the hash map when all prefix sums are distinct.
π§βπ» Code (C++)
class Solution {
public:
int countBalanced(vector<string>& arr) {
int res = 0, sum = 0;
unordered_map<int, int> mp{{0, 1}};
for (string& s : arr) {
int score = 0;
for (char c : s) score += (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') ? 1 : -1;
res += mp[sum += score]++;
}
return res;
}
};
β Code (Java)
class Solution {
public int countBalanced(String[] arr) {
Map<Integer, Integer> mp = new HashMap<>();
mp.put(0, 1);
int sum = 0, res = 0;
for (String s : arr) {
for (char c : s.toCharArray())
sum += "aeiou".indexOf(c) >= 0 ? 1 : -1;
res += mp.getOrDefault(sum, 0);
mp.put(sum, mp.getOrDefault(sum, 0) + 1);
}
return res;
}
}
π Code (Python)
class Solution:
def countBalanced(self, arr):
mp, s, res = {0: 1}, 0, 0
for string in arr:
s += sum(1 if c in 'aeiou' else -1 for c in string)
res += mp.get(s, 0)
mp[s] = mp.get(s, 0) + 1
return res
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated