Longest subsequence consisting of alternate vowels and consonants
Last Updated :
16 Sep, 2023
Given a non-empty string S, the task is to print the longest subsequence from the string S which contains alternating vowels and consonants.
Note: If multiple such subsequences exist having the same length, print the subsequence having the maximum sum of ASCII values of its characters.
Examples:
Input: S = “geeksforgeeks”
Output: gesores
Explanation: “gekorek”, “gekores”, “gekogek”, “gekoges”, “gesorek”, “gesores”, “gesogek”, “gesoges”, “geforek”, “gefores”, “gefogek” and “gefoges” are the possible longest subsequences with alternating consonants and vowels. “gesores” is the subsequence with maximum sum of ASCII values of characters and hence it is the solution.
Input: S = “ababababab”
Output: ababababab
Explanation: “ababababab” is the longest possible subsequence containing alternating vowels and consonants.
Approach:
Follow the steps below to solve the problem:
- Store the ASCII value of the first character of S as the maximum of the current block (maxi) and type of the character in flag. If the character is consonant, set flag as 0 and 1 otherwise.
- Traverse through the rest of the string.
- For every character, check if it belongs to the same block as that of the previous character or not.
- If it belongs to same block, update maxi to max(maxi, ASCII value of ith character).
- Otherwise, append the character with ASCII value maxi to the answer. Store the ASCII value of current ith character as maxi. Update flag to (flag + 1)%2 to denote the type of the current character.
- After traversal of entire string, add the character with ASCII value maxi to the answer. Print the final string representing the subsequence.
Below code is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int isVowel( char c)
{
if (c == 'a' || c == 'e' ||
c == 'i' || c == 'o' ||
c == 'u' )
return 1;
return 0;
}
string Subsequence(string str)
{
int n = str.length();
int flag = 0;
if (isVowel(str[0]) == 1)
flag = 1;
int maxi = ( int )str[0];
string ans = "" ;
for ( int i = 1; i < n; i++)
{
if (isVowel(str[i]) == flag)
{
maxi = max(maxi, ( int )str[i]);
}
else
{
ans += ( char )(maxi);
maxi = ( int )str[i];
flag = (flag + 1) % 2;
}
}
ans += ( char )(maxi);
return ans;
}
int main()
{
string str = "geeksforgeeks" ;
cout << (Subsequence(str));
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
class GFG {
static int isVowel( char c)
{
if (c == 'a' || c == 'e'
|| c == 'i' || c == 'o'
|| c == 'u' )
return 1 ;
return 0 ;
}
static String Subsequence(String str)
{
int n = str.length();
int flag = 0 ;
if (isVowel(str.charAt( 0 )) == 1 )
flag = 1 ;
int maxi = ( int )str.charAt( 0 );
String ans = "" ;
for ( int i = 1 ; i < n; i++) {
if (isVowel(str.charAt(i)) == flag) {
maxi = Math.max(maxi,
( int )str.charAt(i));
}
else {
ans += ( char )(maxi);
maxi = ( int )str.charAt(i);
flag = (flag + 1 ) % 2 ;
}
}
ans += ( char )(maxi);
return ans;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.println(Subsequence(str));
}
}
|
Python3
def isVowel(c):
vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
if (c in vowels):
return True
return False
def Subsequence( str ):
ans = ''
flag = (isVowel( str [ 0 ]))
maxi = ord ( str [ 0 ])
for i in range ( 1 , len ( str )):
if (isVowel( str [i]) = = flag):
maxi = max (maxi, ord ( str [i]))
else :
ans = ans + chr (maxi)
maxi = ord ( str [i])
flag = not (flag)
ans = ans + chr (maxi)
return ans
if __name__ = = "__main__" :
input_string = 'geeksforgeeks'
print (Subsequence(input_string))
|
C#
using System;
class GFG{
static int isVowel( char c)
{
if (c == 'a' || c == 'e' ||
c == 'i' || c == 'o' ||
c == 'u' )
return 1;
return 0;
}
static String Subsequence(String str)
{
int n = str.Length;
int flag = 0;
if (isVowel(str[0]) == 1)
flag = 1;
int maxi = ( int )str[0];
String ans = "" ;
for ( int i = 1; i < n; i++)
{
if (isVowel(str[i]) == flag)
{
maxi = Math.Max(maxi, ( int )str[i]);
}
else
{
ans += ( char )(maxi);
maxi = ( int )str[i];
flag = (flag + 1) % 2;
}
}
ans += ( char )(maxi);
return ans;
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
Console.WriteLine(Subsequence(str));
}
}
|
Javascript
<script>
function isVowel(c)
{
if (c == 'a' || c == 'e' ||
c == 'i' || c == 'o' ||
c == 'u' )
return 1;
return 0;
}
function Subsequence(str)
{
var n = str.length;
var flag = 0;
if (isVowel(str[0]) == 1)
flag = 1;
var maxi = (str[0].charCodeAt(0));
var ans = "" ;
for ( var i = 1; i < n; i++)
{
if (isVowel(str[i]) == flag)
{
maxi = Math.max(maxi, str[i].charCodeAt(0));
}
else
{
ans += String.fromCharCode(maxi);
maxi = str[i].charCodeAt(0);
flag = (flag + 1) % 2;
}
}
ans += String.fromCharCode(maxi);
return ans;
}
var str = "geeksforgeeks" ;
document.write(Subsequence(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N), where N is the length of the given string.
Method 2: Using Recursion
Approach:
- The given problem can be solved using recursion where we generate all possible subsequences of the given string and check if they contain alternating vowels and consonants.
- If a subsequence satisfies this condition, then we check if it is longer than the current longest subsequence and update the longest subsequence accordingly.
- The recursion continues until we have generated all possible subsequences of the given string.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool isVowel( char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ;
}
string longestSubsequence(string s, string current, string longest) {
if (s.length() == 0) {
bool isAlternate = true ;
int sum = 0;
for ( int i = 0; i < current.length() - 1; i++) {
if (isVowel(current[i]) == isVowel(current[i + 1])) {
isAlternate = false ;
break ;
}
}
if (isAlternate) {
if (current.length() > longest.length() || (current.length() == longest.length() && accumulate(current.begin(), current.end(), 0) > accumulate(longest.begin(), longest.end(), 0))) {
longest = current;
}
}
return longest;
}
longest = longestSubsequence(s.substr(1), current + s[0], longest);
longest = longestSubsequence(s.substr(1), current, longest);
return longest;
}
int main() {
string s= "geeksforgeeks" ;
string longest = longestSubsequence(s, "" , "" );
cout << longest << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static boolean isVowel( char c)
{
return c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' ;
}
public static String longestSubsequence(String s,
String current,
String longest)
{
if (s.length() == 0 ) {
boolean isAlternate = true ;
for ( int i = 0 ; i < current.length() - 1 ; i++) {
if (isVowel(current.charAt(i))
== isVowel(current.charAt(i + 1 ))) {
isAlternate = false ;
break ;
}
}
if (isAlternate) {
if (current.length() > longest.length()
|| (current.length() == longest.length()
&& getASCIISum(current)
> getASCIISum(longest))) {
longest = current;
}
}
return longest;
}
longest = longestSubsequence(
s.substring( 1 ), current + s.charAt( 0 ), longest);
longest = longestSubsequence(s.substring( 1 ),
current, longest);
return longest;
}
public static int getASCIISum(String s)
{
int sum = 0 ;
for ( char c : s.toCharArray()) {
sum += c;
}
return sum;
}
public static void main(String[] args)
{
String s = "geeksforgeeks" ;
String longest = longestSubsequence(s, "" , "" );
System.out.println(longest);
}
}
|
Python
def is_vowel(c):
return c = = 'a' or c = = 'e' or c = = 'i' or c = = 'o' or c = = 'u'
def longest_subsequence(s, current, longest):
if len (s) = = 0 :
is_alternate = True
for i in range ( len (current) - 1 ):
if is_vowel(current[i]) = = is_vowel(current[i + 1 ]):
is_alternate = False
break
if is_alternate:
if len (current) > len (longest) or ( len (current) = = len (longest) and sum ( ord (c) for c in current) > sum ( ord (c) for c in longest)):
longest = current
return longest
longest = longest_subsequence(s[ 1 :], current + s[ 0 ], longest)
longest = longest_subsequence(s[ 1 :], current, longest)
return longest
if __name__ = = "__main__" :
s = "geeksforgeeks"
longest = longest_subsequence(s, " ", " ")
print (longest)
|
C#
using System;
class GFG {
static bool IsVowel( char c)
{
return c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u' ;
}
static string LongestSubsequence( string s,
string current,
string longest)
{
if (s.Length == 0) {
bool isAlternate = true ;
for ( int i = 0; i < current.Length - 1; i++) {
if (IsVowel(current[i])
== IsVowel(current[i + 1])) {
isAlternate = false ;
break ;
}
}
if (isAlternate) {
if (current.Length > longest.Length
|| (current.Length == longest.Length
&& GetAsciiSum(current)
> GetAsciiSum(longest))) {
longest = current;
}
}
return longest;
}
longest = LongestSubsequence(
s.Substring(1), current + s[0], longest);
longest = LongestSubsequence(s.Substring(1),
current, longest);
return longest;
}
static int GetAsciiSum( string s)
{
int sum = 0;
foreach ( char c in s) { sum += ( int )c; }
return sum;
}
static void Main()
{
string s = "geeksforgeeks" ;
string longest = LongestSubsequence(s, "" , "" );
Console.WriteLine(longest);
}
}
|
Javascript
function isVowel(c) {
return c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u' ;
}
function longestSubsequence(s, current, longest) {
if (s.length === 0) {
let isAlternate = true ;
for (let i = 0; i < current.length - 1; i++) {
if (isVowel(current[i]) === isVowel(current[i + 1])) {
isAlternate = false ;
break ;
}
}
if (isAlternate) {
if (current.length > longest.length || (current.length === longest.length && [...current].reduce((acc, val) => acc + val.charCodeAt(0), 0) > [...longest].reduce((acc, val) => acc + val.charCodeAt(0), 0))) {
longest = current;
}
}
return longest;
}
longest = longestSubsequence(s.substr(1), current + s[0], longest);
longest = longestSubsequence(s.substr(1), current, longest);
return longest;
}
function main() {
const s = "geeksforgeeks" ;
const longest = longestSubsequence(s, "" , "" );
console.log(longest);
}
main();
|
Time Complexity: O(2^n), where n is the length of the given string.
Auxiliary Space: O(1), No extra space is being used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...