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: 7
Explanation: 
All possible substrings with even number of vowels are:
Substring              Vowels
{abcde}                     2
{b}                            0
{bc}                          0
{bcd}                        0
{c}                            0
{cd}                          0
{d}                           0

Input: N=4, S=”geeks”
Ouput: 6

Naive Approach:
The simplest approach to solve the problem is to generate all possible substrings of the given string and for each substring, count the number of vowels and check if it is even or not. If found to be even, increase count. Finally, after checking for all substrings, print the value of count as the answer.



Below is the implementation of the 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;
  
// Utility function to check 
// if a character is a vowel 
bool isVowel(char c)
{
    if (c == 'a' || c == 'e' || 
        c == 'i' || c == 'o' || 
        c == 'u')
        return true;
  
    return false;
}
  
// Function to calculate and return the
// count of substrings with even number
// of vowels
void countSubstrings(string s, int n)
{
  
    // Stores the count of substrings
    int result = 0;
  
    for(int i = 0; i < n; i++)
    {
        int count = 0;
        for(int j = i; j < n; j++) 
        {
  
            // If the current character
            // is a vowel
            if (isVowel(s[j])) 
            {
                  
                // Increase count
                count++;
            }
  
            // If substring contains
            // even number of vowels
            if (count % 2 == 0)
  
                // Increase the answer
                result++;
        }
    }
  
    // Print the final answer
    cout << result;
}
  
// Driver Code
int main()
{
    int n = 5;
    string s = "abcde";
      
    countSubstrings(s, n);
    return 0;
}
  
// This code is contributed by Amit Katiyar

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
class GFG {
  
    // Utility function to check
    // if a character is a vowel
    static boolean isVowel(char c)
    {
        if (c == 'a' || c == 'e' || c == 'i'
            || c == 'o' || c == 'u')
            return true;
  
        return false;
    }
  
    // Function to calculate and return the
    // count of substrings with even number
    // of vowels
    static void countSubstrings(String s, int n)
    {
  
        // Stores the count of substrings
        int result = 0;
  
        for (int i = 0; i < n; i++) {
            int count = 0;
            for (int j = i; j < n; j++) {
  
                // If the current character
                // is a vowel
                if (isVowel(s.charAt(j))) {
  
                    // Increase count
                    count++;
                }
  
                // If substring contains
                // even number of vowels
                if (count % 2 == 0)
  
                    // Increase the answer
                    result++;
            }
        }
  
        // Print the final answer
        System.out.println(result);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int n = 5;
        String s = "abcde";
        countSubstrings(s, n);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to implement
# the above approach
  
# Utility function to check
# if a character is a vowel
def isVowel(c):
  
    if (c == 'a' or c == 'e' or 
        c == 'i' or c == 'o' or 
        c == 'u'):
        return True
  
    return False
  
# Function to calculate and return the
# count of substrings with even number
# of vowels
def countSubstrings(s, n):
  
    # Stores the count of substrings
    result = 0
  
    for i in range(n):
        count = 0
        for j in range(i, n):
  
            # If the current character
            # is a vowel
            if (isVowel(s[j])):
  
                #Increase count
                count += 1
  
            # If substring contains
            # even number of vowels
            if (count % 2 == 0):
  
                #Increase the answer
                result += 1
  
    # Prthe final answer
    print(result)
  
# Driver Code
if __name__ == '__main__':
  
    n = 5
    s = "abcde"
    countSubstrings(s, n)
  
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
  
class GFG{
  
// Utility function to check
// if a character is a vowel
static bool isVowel(char c)
{
    if (c == 'a' || c == 'e' || c == 'i' || 
        c == 'o' || c == 'u')
        return true;
  
    return false;
}
  
// Function to calculate and return the
// count of substrings with even number
// of vowels
static void countSubstrings(String s, int n)
{
  
    // Stores the count of substrings
    int result = 0;
  
    for(int i = 0; i < n; i++)
    {
        int count = 0;
        for(int j = i; j < n; j++) 
        {
  
            // If the current character
            // is a vowel
            if (isVowel(s[j])) 
            {
  
                // Increase count
                count++;
            }
  
            // If substring contains
            // even number of vowels
            if (count % 2 == 0)
  
                // Increase the answer
                result++;
        }
    }
  
    // Print the final answer
    Console.WriteLine(result);
}
  
// Driver Code
public static void Main(String[] args)
{
    int n = 5;
    String s = "abcde";
      
    countSubstrings(s, n);
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Output: 

7

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach:
Follow the steps below to optimize the above approach:

  • Initialize a cumulative count modulo array temp[], such that:

           temp[0] : Stores count of substrings having even number of vowels.
           temp[1] : Stores count of substrings having odd number of vowels.

  • Any substring [Si, Sj] will contain even number of vowels if the number of vowels in [S0, Si-1], and the number of vowels in [S0, Sj] have the same parity, i.e. either they are both even or both odd.
  • Since the count of substrings with even number of vowels and odd number of vowels are stored in temp[], then, by using handshaking lemma:

         Total count of substrings = (temp[0] * (temp[0] – 1))/2 + (temp[1] * (temp[1] – 1))/2

Below is the implementation of the 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;
  
// Utility function to check
// if a character is a vowel
bool isVowel(char c)
{
    if (c == 'a' || c == 'e' || 
        c == 'i' || c == 'o' || 
        c == 'u')
        return true;
  
    return false;
}
  
// Function to calculate and return the
// count of substrings with even number
// of vowels
void countSubstrings(string s, int n)
{
      
    // Stores the count of substrings
    // with even and odd number of
    // vowels respectively
    int temp[] = { 1, 0 };
  
    int result = 0, sum = 0;
    for(int i = 0; i <= n - 1; i++)
    {
          
        // Update count of vowels modulo 2
        // in sum to obtain even or odd
        sum += (isVowel(s[i]) ? 1 : 0);
        sum %= 2;
  
        // Increment even/odd count
        temp[sum]++;
    }
  
    // Count substrings with even number
    // of vowels using Handshaking Lemma
    result += ((temp[0] * (temp[0] - 1)) / 2);
    result += ((temp[1] * (temp[1] - 1)) / 2);
  
    cout << result;
}
  
// Driver Code
int main()
{
    int n = 5;
    string s = "abcde";
      
    countSubstrings(s, n);
}
  
// This code is contributed by Amit Katiyar

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
class GFG {
  
    // Utility function to check
    // if a character is a vowel
    static boolean isVowel(char c)
    {
        if (c == 'a' || c == 'e' || c == 'i'
            || c == 'o' || c == 'u')
            return true;
  
        return false;
    }
  
    // Function to calculate and return the
    // count of substrings with even number
    // of vowels
    static void countSubstrings(String s, int n)
    {
        // Stores the count of substrings
        // with even and odd number of
        // vowels respectively
        int temp[] = { 1, 0 };
  
        int result = 0, sum = 0;
        for (int i = 0; i <= n - 1; i++) {
  
            // Update count of vowels modulo 2
            // in sum to obtain even or odd
            sum += (isVowel(s.charAt(i)) ? 1 : 0);
            sum %= 2;
  
            // Increment even/odd count
            temp[sum]++;
        }
  
        // Count substrings with even number
        // of vowels using Handshaking Lemma
        result += ((temp[0] * (temp[0] - 1)) / 2);
        result += ((temp[1] * (temp[1] - 1)) / 2);
  
        System.out.println(result);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int n = 5;
        String s = "abcde";
        countSubstrings(s, n);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
  
# Utility function to check
# if a character is a vowel
def isVowel(c):
      
    if (c == 'a' or c == 'e' or
        c == 'i' or c == 'o' or 
        c == 'u'):
        return True;
  
    return False;
  
# Function to calculate and return the
# count of substrings with even number
# of vowels
def countSubstrings(s, n):
      
    # Stores the count of substrings
    # with even and odd number of
    # vowels respectively
    temp = [1, 0];
  
    result = 0;
    sum = 0;
    for i in range(0, n):
          
        # Update count of vowels modulo 2
        # in sum to obtain even or odd
        sum += (1 if isVowel(s[i]) else 0);
        sum %= 2;
  
        # Increment even/odd count
        temp[sum] += 1;
  
    # Count substrings with even number
    # of vowels using Handshaking Lemma
    result += ((temp[0] * (temp[0] - 1)) // 2);
    result += ((temp[1] * (temp[1] - 1)) // 2);
  
    print(result);
  
# Driver Code
if __name__ == '__main__':
      
    n = 5;
    s = "abcde";
      
    countSubstrings(s, n);
  
# This code is contributed by amal kumar choubey

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to implement
// the above approach
using System;
class GFG {
   
  // Utility function to check
  // if a character is a vowel
  static bool isVowel(char c)
  {
    if (c == 'a' || c == 'e' || c == 'i' || 
        c == 'o' || c == 'u')
      return true;
  
    return false;
  }
  
  // Function to calculate and return the
  // count of substrings with even number
  // of vowels
  static void countSubstrings(String s, int n)
  {
    // Stores the count of substrings
    // with even and odd number of
    // vowels respectively
    int []temp = { 1, 0 };
  
    int result = 0, sum = 0;
    for (int i = 0; i <= n - 1; i++) 
    {
      // Update count of vowels modulo 2
      // in sum to obtain even or odd
      sum += (isVowel(s[i]) ? 1 : 0);
      sum %= 2;
  
      // Increment even/odd count
      temp[sum]++;
    }
  
    // Count substrings with even number
    // of vowels using Handshaking Lemma
    result += ((temp[0] * (temp[0] - 1)) / 2);
    result += ((temp[1] * (temp[1] - 1)) / 2);
  
    Console.Write(result);
  }
  
  // Driver Code
  public static void Main(string[] args)
  {
    int n = 5;
    String s = "abcde";
    countSubstrings(s, n);
  }
}
  
// This code is contributed by rock_cool 

chevron_right


Output: 

7

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.




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.