Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Longest Substring having equal count of Vowels and Consonants

  • Last Updated : 21 May, 2021

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 an equal number of vowels and consonants.

Examples:

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

Input: S = “qwertyuiop” 
Output:
Explanation: 
The 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 lengths 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 the above approach:

C++




// 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;
}

Java




// 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

Python3




# 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

C#




// 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

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to return the length of
// the longest subString having equal
// number of vowel and consonant
function maxsubStringLength(S, N)
{
    let arr = Array.from({length: N}, (_, i) => 0);
      
    // Generate the array
    for(let 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
    let maxLen = 0;
      
    // Stores the sum of subarray
    let curr_sum = 0;
      
    // Map to store indices of the sum
    let hash = new Map();
      
    // Loop through the array
    for(let 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.has(curr_sum))
            maxLen = Math.max(maxLen,
                              i - hash.get(curr_sum));
                                
        // Store the index of the sum
        else
          
            // hash[curr_sum] = i;
            hash.set(curr_sum, i);
    }
      
    // Return the maximum
    // length of required subString
    return maxLen;
}
 
// Driver code
 
    let S = "geeksforgeeks";
    let n = S.length;
      
    document.write(maxsubStringLength(S.split(''), n));
 
</script>
Output: 
10

 

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!