Given a string S, the task is to check if the string can be split into two substrings such that the number of vowels in both of them are equal. If found to be true, then print “Yes”. Otherwise, print “No”.
Examples:
Input: S = “geeks”
Output: Yes
Explanation: Splitting the strings into substrings “ge” (count of vowels = 1) and “eks” (count of vowels = 1) satisfies the condition.Input: S = “textbook”
Output: No
Naive Approach: The simplest approach to solve this problem is to traverse the given string S and partition the string into two substrings at every possible indices. For each such split, check if the two substrings have same number of vowels present in them or not. If found to be true, then print “Yes” else print “No”.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by pre-calculating the total number of vowels in the string. Follow the steps below to solve the problem:
- Initialize two variables, say totalVowels and vowelsTillNow, to store the total number of vowels and the current count of vowels respectively.
- Now traverse the string S and count all the vowels and store it in the totalVowels.
- Now, again traverse the string S and decrement totalVowels by 1 and increment vowelsTillNow by 1, if a vowel occurs.Check if totalVowels becomes equal to vowelsTillNow at any point or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Java
// Java program for the above approach import java.io.*; class GFG { // Function to check if any // character is a vowel or not public static boolean isVowel(char ch) { // Lowercase vowels if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; // Uppercase vowels if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') return true; // Otherwise return false; } // Function to check if string S // can be split into two substrings // with equal number of vowels public static String containsEqualStrings(String S) { // Stores the count of vowels // in the string S int totalVowels = 0; // Traverse over the string for (int i = 0; i < S.length(); i++) { // If S[i] is vowel if (isVowel(S.charAt(i))) totalVowels++; } // Stores the count of vowels // upto the current index int vowelsTillNow = 0; // Traverse over the string for (int i = 0; i < S.length(); i++) { // If S[i] is vowel if (isVowel(S.charAt(i))) { vowelsTillNow++; totalVowels--; // If vowelsTillNow and // totalVowels are equal if (vowelsTillNow == totalVowels) { return "Yes"; } } } // Otherwise return "No"; } // Driver Code public static void main(String[] args) { String S = "geeks"; System.out.println( containsEqualStrings(S)); } } |
Yes
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

