Check if a string can be split into two substrings with equal number of vowels
Last Updated :
07 Nov, 2023
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 index. For each such split, check if the two substrings have the same number of vowels present in them or not. If found to be true, then print "Yes" else print "No".
C++
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if any
// character is a vowel or not
bool isVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U');
}
// Function to check if string S
// can be split into two substrings
// with equal number of vowels
int containsEqualStrings(string S)
{
int n = S.length();
bool found = false;
// Traversing in the given string
for (int i = 0; i < n - 1; i++) {
int vowelsLeft = 0, vowelsRight = 0;
// Count the number of vowels in left substring
for (int j = 0; j <= i; j++) {
if (isVowel(S[j])) {
vowelsLeft++;
}
}
// Count the number of vowels in right substring
for (int j = i + 1; j < n; j++) {
if (isVowel(S[j])) {
vowelsRight++;
}
}
// check if substrings has equal
// number of vowels
if (vowelsLeft == vowelsRight) {
found = true;
break;
}
}
if (found) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
// Driver Code
int main()
{
string S = "geeks";
containsEqualStrings(S);
}
// This code is contributed by Pushpesh Raj.
Java
// Java code for above approach
import java.io.*;
import java.util.*;
public class Main {
// Function to check if any
// character is a vowel or not
static boolean isVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U');
}
// Function to check if string S
// can be split into two substrings
// with equal number of vowels
static int containsEqualStrings(String S)
{
int n = S.length();
boolean found = false;
// Traversing in the given string
for (int i = 0; i < n - 1; i++) {
int vowelsLeft = 0, vowelsRight = 0;
// Count the number of vowels in left substring
for (int j = 0; j <= i; j++) {
if (isVowel(S.charAt(j))) {
vowelsLeft++;
}
}
// Count the number of vowels in right substring
for (int j = i + 1; j < n; j++) {
if (isVowel(S.charAt(j))) {
vowelsRight++;
}
}
// check if substrings has equal
// number of vowels
if (vowelsLeft == vowelsRight) {
found = true;
break;
}
}
if (found) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
return 0;
}
// Driver Code
public static void main(String[] args)
{
String S = "geeks";
containsEqualStrings(S);
}
}
Python3
# Function to check if any
# character is a vowel or not
def isVowel(c):
return (c == 'a' or c == 'e' or c == 'i' or c == 'o'
or c == 'u' or c == 'A' or c == 'E' or c == 'I'
or c == 'O' or c == 'U')
# Function to check if string S
# can be split into two substrings
# with equal number of vowels
def containsEqualStrings(str):
n = len(str)
found = False
# Traversing in the given string
for i in range(n - 1):
vowelsLeft = 0
vowelsRight = 0
# Count the number of vowels in left substring
for j in range(i + 1):
if isVowel(str[j]):
vowelsLeft += 1
# Count the number of vowels in right substring
for j in range(i + 1, n):
if isVowel(str[j]):
vowelsRight += 1
# check if substrings has equal
# number of vowels
if vowelsLeft == vowelsRight:
found = True
break
if found:
print("Yes")
else:
print("No")
# Driver C
str = "geeks"
containsEqualStrings(str)
# This code is contributed by Jay
C#
// C# code for above approach
using System;
class Program {
// Function to check if any
// character is a vowel or not
static bool IsVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E'
|| c == 'I' || c == 'O' || c == 'U');
}
// Function to check if string S
// can be split into two substrings
// with equal number of vowels
static void ContainsEqualStrings(string S)
{
int n = S.Length;
bool found = false;
// Traversing in the given string
for (int i = 0; i < n - 1; i++) {
int vowelsLeft = 0, vowelsRight = 0;
// Count the number of vowels in left substring
for (int j = 0; j <= i; j++) {
if (IsVowel(S[j])) {
vowelsLeft++;
}
}
// Count the number of vowels in right substring
for (int j = i + 1; j < n; j++) {
if (IsVowel(S[j])) {
vowelsRight++;
}
}
// check if substrings has equal
// number of vowels
if (vowelsLeft == vowelsRight) {
found = true;
break;
}
}
if (found) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
// Driver Code
static void Main()
{
string S = "geeks";
ContainsEqualStrings(S);
}
}
// This code is contributed by sarojmcy2e
JavaScript
// JavaScript code for above approach
// Function to check if any
// character is a vowel or not
function isVowel(c) {
return (c === 'a' || c === 'e' || c === 'i' || c === 'o' ||
c === 'u' || c === 'A' || c === 'E' || c === 'I' ||
c === 'O' || c === 'U');
}
// Function to check if string S
// can be split into two substrings
// with equal number of vowels
function containsEqualStrings(S) {
const n = S.length;
let found = false;
// Traversing in the given string
for (let i = 0; i < n - 1; i++) {
let vowelsLeft = 0, vowelsRight = 0;
// Count the number of vowels in left substring
for (let j = 0; j <= i; j++) {
if (isVowel(S[j])) {
vowelsLeft++;
}
}
// Count the number of vowels in right substring
for (let j = i + 1; j < n; j++) {
if (isVowel(S[j])) {
vowelsRight++;
}
}
// check if substrings has equal
// number of vowels
if (vowelsLeft === vowelsRight) {
found = true;
break;
}
}
if (found) {
console.log("Yes");
}
else {
console.log("No");
}
}
// Driver Code
const S = "geeks";
containsEqualStrings(S);
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 become 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:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if any
// character is a vowel or not
bool 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
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.size(); i++)
{
// If S[i] is vowel
if (isVowel(S[i]))
totalVowels++;
}
// Stores the count of vowels
// upto the current index
int vowelsTillNow = 0;
// Traverse over the string
for (int i = 0;
i < S.size(); i++)
{
// If S[i] is vowel
if (isVowel(S[i]))
{
vowelsTillNow++;
totalVowels--;
// If vowelsTillNow and
// totalVowels are equal
if (vowelsTillNow
== totalVowels)
{
return "Yes";
}
}
}
// Otherwise
return "No";
}
// Driver Code
int main()
{
string S = "geeks";
cout<<(containsEqualStrings(S));
}
// This code is contributed by mohit kumar 29.
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));
}
}
Python3
# Python3 program for the above approach
# Function to check if any
# character is a vowel or not
def isVowel(ch):
# Lowercase vowels
if (ch == 'a' or ch == 'e' or
ch == 'i' or ch == 'o' or
ch == 'u'):
return True
# Uppercase vowels
if (ch == 'A' or ch == 'E' or
ch == 'I' or ch == 'O' or
ch == 'U'):
return True
# Otherwise
return False
# Function to check if string S
# can be split into two substrings
# with equal number of vowels
def containsEqualStrings(S):
# Stores the count of vowels
# in the string S
totalVowels = 0
# Traverse over the string
for i in range(len(S)):
# If S[i] is vowel
if (isVowel(S[i])):
totalVowels += 1
# Stores the count of vowels
# upto the current index
vowelsTillNow = 0
# Traverse over the string
for i in range(len(S)):
# If S[i] is vowel
if (isVowel(S[i])):
vowelsTillNow += 1
totalVowels -= 1
# If vowelsTillNow and
# totalVowels are equal
if (vowelsTillNow == totalVowels):
return "Yes"
# Otherwise
return "No"
# Driver Code
if __name__ == "__main__":
S = "geeks"
print(containsEqualStrings(S))
# This code is contributed by ukasp
C#
// C# program for the above approach
using System;
class GFG
{
// Function to check if any
// character is a vowel or not
public static bool 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[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[i])) {
vowelsTillNow++;
totalVowels--;
// If vowelsTillNow and
// totalVowels are equal
if (vowelsTillNow
== totalVowels) {
return "Yes";
}
}
}
// Otherwise
return "No";
}
// Driver Code
static public void Main()
{
string S = "geeks";
Console.WriteLine(
containsEqualStrings(S));
}
}
// This code is contributed by code_hunt.
JavaScript
<script>
// JavaScript program for the above approach
// Function to check if any
// character is a vowel or not
function isVowel(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
function containsEqualStrings(S) {
// Stores the count of vowels
// in the string S
var totalVowels = 0;
// Traverse over the string
for (var i = 0; i < S.length; i++) {
// If S[i] is vowel
if (isVowel(S[i])) totalVowels++;
}
// Stores the count of vowels
// upto the current index
var vowelsTillNow = 0;
// Traverse over the string
for (var i = 0; i < S.length; i++) {
// If S[i] is vowel
if (isVowel(S[i])) {
vowelsTillNow++;
totalVowels--;
// If vowelsTillNow and
// totalVowels are equal
if (vowelsTillNow === totalVowels) {
return "Yes";
}
}
}
// Otherwise
return "No";
}
// Driver Code
var S = "geeks";
document.write(containsEqualStrings(S));
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 3: Count the number of vowels if the count is even then it is possible that we can divide it into two sub strings having same vowels else not.
This is simple and efficient approach. The following steps to follow to solve the problem:
1. Define a function "isVowel" that returns true if the input character is a vowel else false.
2. Define another function "isEqualVowels" that takes a string input "s" and counts the number of vowels present in the string.
3. If the count of vowels is even, print "Yes" ( It means we can divide vowels into two sub-strings). If the count of vowels is odd, print "No".
4.In the main function, taken a string "s" and call the "isEqualVowels" function with the string as an argument.
Below is the implementation of the above approach:
C++
// C++ code for above approach
#include <iostream>
using namespace std;
// Function to character is vowel or not.
bool isVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U');
}
void isEqualVowels(string s)
{
int len = s.length(); // length of the string
int count_vowels = 0;
// counting no. of vowels present in the string
for(int i = 0; i<len; i++)
{
if(isVowel(s[i]))
count_vowels++;
}
if(count_vowels%2==0) // count of vowels is even the print Yes
cout<<"Yes"<<endl;
else // else print No
cout<<"No"<<endl;
}
int main() {
string s = "geeks"; // Input taken
isEqualVowels(s);
return 0;
}
Java
import java.io.*;
class GFG {
static boolean isVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U');
}
static void isEqualVowels(String s)
{
int len = s.length(); // length of the string
int count_vowels = 0;
// counting no. of vowels present in the string
for(int i = 0; i<len; i++)
{
if(isVowel(s.charAt(i)))
count_vowels++;
}
if(count_vowels%2==0) // count of vowels is even the print Yes
System.out.println("Yes");
else // else print No
System.out.println("No");
}
// Driver code
public static void main(String []args)
{
String s = "geeks"; // Input taken
isEqualVowels(s);
}
}
Python3
# Function to check if a character is a vowel or not
def is_vowel(c):
return c.lower() in ['a', 'e', 'i', 'o', 'u']
# Function to check if the count of vowels in a string is even or not
def is_equal_vowels(s):
count_vowels = sum(1 for char in s if is_vowel(char)) # Counting the number of vowels
# in the string
if count_vowels % 2 == 0: # If count of vowels is even, print 'Yes'
print("Yes")
else: # If count of vowels is odd, print 'No'
print("No")
def main():
s = "geeks" # Input string
is_equal_vowels(s)
if __name__ == "__main__":
main()
C#
using System;
class Program
{
// Function to check if a character is a vowel or not.
static bool IsVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U');
}
static void IsEqualVowels(string s)
{
int len = s.Length; // Length of the string
int countVowels = 0;
// Count the number of vowels present in the string
for (int i = 0; i < len; i++)
{
if (IsVowel(s[i]))
countVowels++;
}
if (countVowels % 2 == 0) // If the count of vowels is even, then print "Yes"
Console.WriteLine("Yes");
else // Otherwise, print "No"
Console.WriteLine("No");
}
// Driver code
static void Main()
{
string s = "geeks"; // Input string
IsEqualVowels(s);
}
}
JavaScript
// JavaScript code for above approach
// Function to character is vowel or not.
function isVowel( c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U');
}
function isEqualVowels( s)
{
let len = s.length; // length of the string
let count_vowels = 0;
// counting no. of vowels present in the string
for(let i = 0; i<len; i++)
{
if(isVowel(s[i]))
count_vowels++;
}
if(count_vowels%2==0) // count of vowels is even the print Yes
document.write("Yes");
else // else print No
document.write("No");
}
let s = "geeks"; // Input taken
isEqualVowels(s);
Time Complexity: O(N), as traversing over the string.
Auxiliary Space: O(1)
Similar Reads
Check if a string can be split into two strings with same number of K-frequent characters
Given a string S and an integer K, the task is to check if it is possible to distribute these characters into two strings such that the count of characters having a frequency K in both strings is equal. If it is possible, then print a sequence consisting of 1 and 2, which denotes which character sho
11 min read
Split a given string into substrings of length K with equal sum of ASCII values
Given a string str of size N and an integer K, the task is to check if the input string can be partitioned into substrings of size K having a constant sum of ASCII values.Examples: Input: str = "abdcbbdba" K = 3 Output: YES Explanation: 3 length substrings {"and", "cbb", "dba"} with sum of their ASC
6 min read
Print all Substrings of a String that has equal number of vowels and consonants
Given a string S, the task is to print all the substrings of a string that has an equal number of vowels and consonants. Examples: Input: "geeks"Output: "ge", "geek", "eeks", "ek" Input: "coding"Output: "co", "codi", "od", "odin", "di", "in" Naive Approach: The basic approach to solve this problem i
13 min read
Check if given String can be split only into subsequences ABC
Given a string S of length N where each character of the string is either 'A', 'B' or 'C'. The task is to find if is it possible to split the string into subsequences "ABC". If it is possible to split then print "Yes". Otherwise, print "No". Examples: Input: S = "ABABCC"Output: YesExplanation:One of
12 min read
Check if a string can be split into substrings starting with N followed by N characters
Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer. Examples: Input: str = "4g12y6hunter" Output: Yes Explanation: Substrings "4g12y" and "6hunter" sat
5 min read
Split Strings into two Substrings whose distinct element counts are equal
Given a string S of length N, the task is to check if a string can be split into two non-intersecting strings such that the number of distinct characters are equal in both. Examples: Input: N = 6, S = "abccba"Output: TrueExplanation: Splitting two strings as "abc" and "cba" has 3 distinct characters
8 min read
Encrypt string with product of number of vowels and consonants in substring of size k
Given a string s and a positive integer k. You need to encrypt the given string such that each substring of size k is represented by an integer, which is obtained by the product of number of vowels and number of consonants in the substring. Examples: Input : s = "hello", k = 2 Output : 1101 k = 2, s
13 min read
Check if the string has a reversible equal substring at the ends
Given a string S consisting of N characters, the task is to check if this string has a reversible equal substring from the start and the end. If yes, print True and then the longest substring present following the given conditions, otherwise print False. Example: Input: S = "abca"Output: TrueaExplan
5 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B
5 min read
Count the number of vowels occurring in all the substrings of given string | Set 2
Given a string str[] of length N of lowercase characters containing 0 or more vowels, the task is to find the count of vowels that occurred in all the substrings of the given string. Examples: Input: str = âabcâ Output: 3The given string âabcâ contains only one vowel = âaâ Substrings of âabcâ are =
5 min read