Length of the longest substring that contains even number of vowels
Last Updated :
14 Jul, 2023
Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring consisting of each vowel an even number of times
Examples:
Input: S= "bcbcbc"
Output: 6
Explanation:
Consider the substring S[0, 5] i.e., "bcbcbc" is the longest substring because all vowels: a, e, i, o and u appear 0(which is even) number of times.
Input: S = "ebbaa"
Output: 4
Naive Approach: The simplest approach to solve the given problem is to generate all possible substrings from the given string S and for each substring, check if the frequency of all vowels in the substring is even or not. If found to be true, then update the maximum length of the string required. After checking for all the substrings, print the maximum length obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using Hashing. The idea is to initialize a string, say temp of size 5 corresponding to the 5 vowels (a, e, i, o, u) with all 0s, where s[i] = 0 indicates that the ith vowel is occurring an even number of times. Now, traverse the given string and find the same state of the string, temp from the map and update the maximum length. Follow the steps below to solve the problem:
- Initialize a variable, say ans as 0 that stores the required result.
- Initialize a string, say temp of size 5 as "00000".
- Create a hashmap, M to store the index of occurrence of string temp and initialize the value of temp in M as -1.
- Traverse the given string S over the range [0, N - 1] using the variable i and perform the following steps:
- If the character S[i] is a vowel, then update the string temp.
- If the string temp is present in the map M then store its value from the map M in a variable X and update the value of ans to the maximum of ans and (i - X).
- Otherwise, update the value of temp in the map M as i.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the length of the
// longest substring having even number
// of vowels
int longestSubstring(string s)
{
// Create two hashmaps
unordered_map<string, int> indexes;
unordered_map<char, int> chars(
{ { 'a', 0 }, { 'e', 1 },
{ 'i', 2 }, { 'o', 3 },
{ 'u', 4 } });
// Keep the track of frequencies
// of the vowels
string evenOdd = "00000";
indexes[evenOdd] = -1;
// Stores the maximum length
int length = 0;
// Traverse the given string S
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
// Find character in the map
auto it = chars.find(c);
// If it is a vowel, then update
// the frequency
if (it != chars.end()) {
evenOdd[it->second]
= evenOdd[it->second]
== '0'
? '1'
: '0';
}
// Find the index of occurrence
// of the string evenOdd in map
auto lastIndex = indexes.find(evenOdd);
if (lastIndex == indexes.end()) {
indexes[evenOdd] = i;
}
// Update the maximum length
else {
length = max(
length, i - lastIndex->second);
}
}
// Print the maximum length
cout << length;
}
// Driver Code
int main()
{
string S = "bcbcbc";
longestSubstring(S);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
// Function to find the length of the
// longest substring having even number
// of vowels
static void longestSubstring(String s)
{
// Create two hashmaps
HashMap<String, Integer> indexes = new HashMap<>();
HashMap<Character, Integer> chars = new HashMap<>(){{
put('a', 0);put('e', 1);
put('i', 2);put('o', 3);
put('u', 4);
}} ;
// Keep the track of frequencies
// of the vowels
String evenOdd = "00000";
indexes.put(evenOdd , -1);
// Stores the maximum length
int length = 0;
// Traverse the given string S
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
// Find character in the map
boolean it = chars.containsKey(c);
// If it is a vowel, then update
// the frequency
if (it != false) {
if(evenOdd.charAt(chars.get(c)) == '0'){
evenOdd = evenOdd.substring(0,chars.get(c)) + '1' + evenOdd.substring(chars.get(c)+1);
}
else{
evenOdd = evenOdd.substring(0,chars.get(c)) + '0' + evenOdd.substring(chars.get(c)+1);
}
}
// Find the index of occurrence
// of the string evenOdd in map
boolean lastIndex = indexes.containsKey(evenOdd);
if (lastIndex == false) {
indexes.put(evenOdd, i);
}
// Update the maximum length
else {
length = Math.max(length, i - indexes.get(evenOdd));
}
}
// Print the maximum length
System.out.println(length);
}
// Driver Code
public static void main(String args[])
{
// Given Input
String S = "bcbcbc";
longestSubstring(S);
}
}
// code is contributed by shinjanpatra
Python3
# Python3 program for the above approach
# Function to find the length of the
# longest substring having even number
# of vowels
def longestSubstring(s):
# Create two hashmaps
indexes = {}
chars = {}
chars['a'] = 0
chars['e'] = 1
chars['i'] = 2
chars['o'] = 3
chars['u'] = 4
# Keep the track of frequencies
# of the vowels
evenOdd = "00000"
evenOdd = [i for i in evenOdd]
indexes["".join(evenOdd)] = -1
# Stores the maximum length
length = 0
# Traverse the given string S
for i in range(len(s)):
c = s[i]
# Find character in the map
# If it is a vowel, then update
# the frequency
if (c in chars):
evenOdd[chars[it]] = '1' if evenOdd[chars[it]] else '0'
# Find the index of occurrence
# of the string evenOdd in map
if ("".join(evenOdd) not in indexes):
indexes["".join(evenOdd)] = i
# Update the maximum length
else:
length = max(
length, i - indexes["".join(evenOdd)])
# Print the maximum length
print(length)
# Driver Code
if __name__ == '__main__':
S = "bcbcbc"
longestSubstring(S)
# This code is contributed by mohit kumar 29
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the length of the
// longest substring having even number
// of vowels
static void LongestSubstring(string s)
{
// Create two dictionaries
Dictionary<string, int> indexes = new Dictionary<string, int>();
Dictionary<char, int> chars = new Dictionary<char, int>()
{
{'a', 0}, {'e', 1},
{'i', 2}, {'o', 3},
{'u', 4}
};
// Keep the track of frequencies
// of the vowels
string evenOdd = "00000";
indexes[evenOdd] = -1;
// Stores the maximum length
int length = 0;
// Traverse the given string S
for (int i = 0; i < s.Length; ++i)
{
char c = s[i];
// Find character in the dictionary
bool it = chars.ContainsKey(c);
// If it is a vowel, then update
// the frequency
if (it != false)
{
if (evenOdd[chars[c]] == '0')
{
evenOdd = evenOdd.Substring(0, chars[c]) + '1' + evenOdd.Substring(chars[c] + 1);
}
else
{
evenOdd = evenOdd.Substring(0, chars[c]) + '0' + evenOdd.Substring(chars[c] + 1);
}
}
// Find the index of occurrence
// of the string evenOdd in dictionary
bool lastIndex = indexes.ContainsKey(evenOdd);
if (lastIndex == false)
{
indexes[evenOdd] = i;
}
// Update the maximum length
else
{
length = Math.Max(length, i - indexes[evenOdd]);
}
}
// Print the maximum length
Console.WriteLine(length);
}
// Driver Code
static void Main(string[] args)
{
// Given Input
string S = "bcbcbc";
LongestSubstring(S);
}
}
// This code is contributed by Pushpesh Raj.
JavaScript
<script>
// JavaScript code for the approach
// Function to find the length of the
// longest substring having even number
// of vowels
function longestSubstring(s)
{
// Create two hashmaps
let indexes = new Map();
let chars = new Map();
chars.set('a',0);
chars.set('e',1);
chars.set('i',2);
chars.set('o',3);
chars.set('u',4);
// Keep the track of frequencies
// of the vowels
let evenOdd = "00000";
indexes.set(evenOdd , -1);
// Stores the maximum length
let length = 0;
// Traverse the given string S
for (let i = 0; i <br s.length; ++i) {
let c = s[i];
// If it is a vowel, then update
// the frequency
if (chars.has(c)) {
evenOdd.set(chars.get(c),(evenOdd.get(chars.get(c)) == '0')? '1': '0');
}
// Find the index of occurrence
// of the string evenOdd in map
if (indexes.has(evenOdd) == false) {
indexes.set(evenOdd,i);
}
// Update the maximum length
else {
length = Math.max(length, i - indexes.get(evenOdd));
}
}
// Print the maximum length
document.write(length,"</br>");
}
// Driver Code
let S = "bcbcbc";
longestSubstring(S);
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Length of the longest substring that does not contain any vowel
Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring that does not contain any vowel. Examples: Input: S = âgeeksforgeeksâOutput: 3The substring "ksf" is the longest substring that does not contain any vowel. The length of this substring is 3
6 min read
Length of the longest substring that do not contain any palindrome
Given a string of lowercase, find the length of the longest substring that does not contain any palindrome as a substring. Examples: Input : str = "daiict" Output : 3 dai, ict are longest substring that do not contain any palindrome as substring Input : str = "a" Output : 0 a is itself a palindrome
6 min read
Length of the longest substring consisting only of vowels in non-increasing order
Given a string S of size N consisting of lowercase alphabets, the task is to print the length of the longest substring consisting only of vowels sorted in non-increasing order. Examples: Input: S = "ueiaoaeiouuoiea"Output: 6Explanation: The only substring which consists only of vowels in non-increas
10 min read
Length of the longest substring with every character appearing even number of times
Content has been removed on Authorâs request.
1 min read
Count of substrings consisting of even number of vowels
Given a string S of length N, the task is to find the number of non-empty substrings having even number of vowels. Examples: Input: N = 5, S = "abcde"Output: 7Explanation: All possible substrings with even number of vowels are:Substring Vowels{abcde} 2{b} 0{bc} 0{bcd} 0{c} 0{cd} 0{d} 0Input: N=4, S=
11 min read
Count the number of vowels occurring in all the substrings of given string
Given a string 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 = {"a",
12 min read
Length of the longest substring with no consecutive same letters
Given a string str, the task is to find the length of the longest sub-string which does not have any pair of consecutive same characters. Examples: Input: str = "abcdde" Output: 4 "abcd" is the longestInput: str = "ccccdeededff" Output: 5 "ededf" is the longest Approach: The following steps can be f
7 min read
Modify the string such that it contains all vowels at least once
Given a string S containing only Uppercase letters, the task is to find the minimum number of replacement of characters needed to get a string with all vowels and if we cannot make the required string then print Impossible. Examples: Input: str = "ABCDEFGHI"Output: AOUDEFGHIExplanation: There are al
11 min read
Length of the smallest substring which contains all vowels
Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1. Example: Input: str = "babeivoucu" Output: 7 Explanation: Smallest substring which contains each vowel atl
15+ min read
Length of longest common subsequence containing vowels
Given two strings X and Y of length m and n respectively. The problem is to find the length of the longest common subsequence of strings X and Y which contains all vowel characters.Examples: Input : X = "aieef" Y = "klaief"Output : aieInput : X = "geeksforgeeks" Y = "feroeeks"Output : eoeeSource:Pay
14 min read