Longest Substring having equal count of Vowels and Consonants

Given a string S consisting of lowercase English letters, the task is to find the length of the longest substring from the given string, having equal number of vowels and consonants.

Examples:

Input: S = “geeksforgeeks” 
Output: 10 
Explanation: 
Substring “eeksforgee” consists of 5 vowels and 5 consonants. Remaining characters are only consonants. Therefore, any longer substring won’t have equal number of vowels and consonants.
Input: S = “qwertyuiop” 
Output:
Explanation: 
Substring “wertyuio” consists of 4 vowels and 4 consonants.

Naive Approach: The simplest solution is to generate all substrings of the given string and for each substring, check if the count of vowels and consonants are equal or not. Finally, print the maximum length of substring obtained having an equal number of vowels and consonants. 
Time Complexity: O(N3
Auxiliary Space: O(1)

Efficient Approach: The idea is to consider an array of length equal to that of the given string, storing 1 and -1 corresponding to vowels and consonants respectively and print the length of the longest sub-array with the sum equal to 0 using HashMap.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the length of
// the longest substring having equal
// number of vowel and consonant
int maxsubstringLength(string S, int N)
{
    int arr[N];
 
    // Generate the array
    for (int i = 0; i < N; i++)
        if (S[i] == 'a' || S[i] == 'e' || S[i] == 'i'
            || S[i] == 'o' || S[i] == 'u')
            arr[i] = 1;
        else
            arr[i] = -1;
 
    // Initialize variable
    // to store result
    int maxLen = 0;
 
    // Stores the sum of subarray
    int curr_sum = 0;
 
    // Map to store indices of the sum
    unordered_map<int, int> hash;
 
    // Loop through the array
    for (int i = 0; i < N; i++) {
        curr_sum += arr[i];
 
        // If sum is 0
        if (curr_sum == 0)
 
            // Count of vowels and consonants
            // are equal
            maxLen = max(maxLen, i + 1);
 
        // Update the maximum length
        // of substring in HashMap
        if (hash.find(curr_sum) != hash.end())
            maxLen = max(maxLen, i - hash[curr_sum]);
 
        // Store the index of the sum
        else
            hash[curr_sum] = i;
    }
 
    // Return the maximum
    // length of required substring
    return maxLen;
}
 
// Driver Code
int main()
{
    string S = "geeksforgeeks";
    int n = sizeof(S) / sizeof(S[0]);
    cout << maxsubstringLength(S, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
// Function to return the length of
// the longest subString having equal
// number of vowel and consonant
static int maxsubStringLength(char[] S, int N)
{
    int arr[] = new int[N];
     
    // Generate the array
    for(int i = 0; i < N; i++)
    if (S[i] == 'a' || S[i] == 'e' ||
        S[i] == 'i' || S[i] == 'o' ||
        S[i] == 'u')
        arr[i] = 1;
    else
        arr[i] = -1;
         
    // Initialize variable
    // to store result
    int maxLen = 0;
     
    // Stores the sum of subarray
    int curr_sum = 0;
     
    // Map to store indices of the sum
    HashMap<Integer, Integer> hash = new HashMap<>();
     
    // Loop through the array
    for(int i = 0; i < N; i++)
    {
        curr_sum += arr[i];
         
        // If sum is 0
        if (curr_sum == 0)
         
            // Count of vowels and consonants
            // are equal
            maxLen = Math.max(maxLen, i + 1);
             
        // Update the maximum length
        // of subString in HashMap
        if (hash.containsKey(curr_sum))
            maxLen = Math.max(maxLen,
                              i - hash.get(curr_sum));
                               
        // Store the index of the sum
        else
         
            // hash[curr_sum] = i;
            hash.put(curr_sum, i);
    }
     
    // Return the maximum
    // length of required subString
    return maxLen;
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "geeksforgeeks";
    int n = S.length();
     
    System.out.print(
        maxsubStringLength(S.toCharArray(), n));
}
}
 
// This code is contributed by PrinciRaj1992

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to return the length of
# the longest substring having equal
# number of vowel and consonant
def maxsubstringLength(S, N):
 
    arr = [0] * N
 
    # Generate the array
    for i in range(N):
        if(S[i] == 'a' or S[i] == 'e' or
           S[i] == 'i' or S[i] == 'o' or
           S[i] == 'u'):
            arr[i] = 1
        else:
            arr[i] = -1
 
    # Initialize variable
    # to store result
    maxLen = 0
 
    # Stores the sum of subarray
    curr_sum = 0
 
    # Map to store indices of the sum
    hash = {}
 
    # Loop through the array
    for i in range(N):
        curr_sum += arr[i]
 
        # If sum is 0
        if(curr_sum == 0):
 
            # Count of vowels and consonants
            # are equal
            maxLen = max(maxLen, i + 1)
 
        # Update the maximum length
        # of substring in HashMap
        if(curr_sum in hash.keys()):
            maxLen = max(maxLen, i - hash[curr_sum])
 
        # Store the index of the sum
        else:
            hash[curr_sum] = i
 
    # Return the maximum
    # length of required substring
    return maxLen
 
# Driver Code
S = "geeksforgeeks"
n = len(S)
 
# Function call
print(maxsubstringLength(S, n))
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to return the length of
// the longest subString having equal
// number of vowel and consonant
static int maxsubStringLength(char[] S, int N)
{
    int []arr = new int[N];
     
    // Generate the array
    for(int i = 0; i < N; i++)
    if (S[i] == 'a' || S[i] == 'e' ||
        S[i] == 'i' || S[i] == 'o' ||
        S[i] == 'u')
        arr[i] = 1;
    else
        arr[i] = -1;
         
    // Initialize variable
    // to store result
    int maxLen = 0;
     
    // Stores the sum of subarray
    int curr_sum = 0;
     
    // Map to store indices of the sum
    Dictionary<int,
                 int> hash = new Dictionary<int,
                                            int>();
     
    // Loop through the array
    for(int i = 0; i < N; i++)
    {
        curr_sum += arr[i];
         
        // If sum is 0
        if (curr_sum == 0)
         
            // Count of vowels and consonants
            // are equal
            maxLen = Math.Max(maxLen, i + 1);
             
        // Update the maximum length
        // of subString in Dictionary
        if (hash.ContainsKey(curr_sum))
            maxLen = Math.Max(maxLen,
                              i - hash[curr_sum]);
                               
        // Store the index of the sum
        else
         
            // hash[curr_sum] = i;
            hash.Add(curr_sum, i);
    }
     
    // Return the maximum
    // length of required subString
    return maxLen;
}
 
// Driver Code
public static void Main(String[] args)
{
    String S = "geeksforgeeks";
    int n = S.Length;
     
    Console.Write(maxsubStringLength(
                    S.ToCharArray(), n));
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output: 

10



 

Time Complexity: O(NlogN) 
Auxiliary Space: O(N)

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.