Longest subsequence with consecutive English alphabets - GeeksforGeeks

13 Aug, 2021
Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets.
Examples:
Input: S = “acbdcfhg”Output: 3Explanation: String “abc” is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence “abc”.
Input: S = “gabbsdcdggbe”Output: 5
Naive Approach: The simplest approach is to generate all possible subsequences of the given string and if there exists any subsequence of the given string that has consecutive characters and is of maximum length then print that length.
Time Complexity: O(2N)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by generating all possible consecutive subsequences of the given string starting from each lowercase alphabets and print the maximum among all the subsequence found. Follow the steps below to solve the problem:
Initialize a variable, say ans, as 0 that stores the maximum length of the consecutive subsequence.
For each character ch over the range [a, z] perform the following:Initialize a variable cnt as 0 that stores the length of a subsequence of consecutive characters starting from ch.Traverse the given string S and if the current character is ch then increment the cnt by 1 and update the current character ch to the next character by (ch + 1).Update ans = max(ans, cnt)
Initialize a variable cnt as 0 that stores the length of a subsequence of consecutive characters starting from ch.
Traverse the given string S and if the current character is ch then increment the cnt by 1 and update the current character ch to the next character by (ch + 1).
Update ans = max(ans, cnt)
After the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of subsequence// starting with character chint findSubsequence(string S, char ch){    // Length of the string    int N = S.length();     // Stores the maximum length    int ans = 0;     // Traverse the given string    for (int i = 0; i < N; i++) {         // If s[i] is required        // character ch        if (S[i] == ch) {             // Increment  ans by 1            ans++;             // Increment  character ch            ch++;        }    }     // Return the current maximum    // length with character ch    return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersint findMaxSubsequence(string S){    // Stores the maximum length of    // consecutive characters    int ans = 0;     for (char ch = 'a'; ch <= 'z'; ch++) {         // Update ans        ans = max(ans, findSubsequence(S, ch));    }     // Return the maximum length of    // subsequence    return ans;} // Driver Codeint main(){    // Input    string S = "abcabefghijk";     // Function Call    cout << findMaxSubsequence(S);     return 0;}
// C# program for the above approachimport java.io.*;import java.util.*;import java.util.Arrays; class GFG{ // Function to find the length of subsequence// starting with character chstatic int findSubsequence(String S, char ch){         // Length of the string    int N = S.length();     // Stores the maximum length    int ans = 0;     // Traverse the given string    for(int i = 0; i < N; i++)    {                 // If s[i] is required        // character ch         if(S.charAt(i) == ch)        {                         // Increment  ans by 1            ans++;             // Increment  character ch            ch++;        }    }     // Return the current maximum    // length with character ch    return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersstatic int findMaxSubsequence(String S){         // Stores the maximum length of    // consecutive characters    int ans = 0;     for(char ch = 'a'; ch <= 'z'; ch++)    {                 // Update ans        ans = Math.max(ans, findSubsequence(S, ch));    }     // Return the maximum length of    // subsequence    return ans;} // Driver Codepublic static void main(String[] args){         // Input    String S = "abcabefghijk";     // Function Call    System.out.print(findMaxSubsequence(S));}} // This code is contributed by shivanisinghss2110
# Python3 program for the above approach # Function to find the length of subsequence# starting with character chdef findSubsequence(S, ch):    # Length of the string    N = len(S)     # Stores the maximum length    ans = 0     # Traverse the given string    for i in range(N):               # If s[i] is required        # character ch        if (S[i] == ch):             # Increment  ans by 1            ans += 1             # Increment  character ch            ch=chr(ord(ch) + 1)     # Return the current maximum    # length with character ch    return ans # Function to find the maximum length# of subsequence of consecutive# charactersdef findMaxSubsequence(S):    #Stores the maximum length of    # consecutive characters    ans = 0     for ch in range(ord('a'),ord('z') + 1):        # Update ans        ans = max(ans, findSubsequence(S, chr(ch)))     # Return the maximum length of    # subsequence    return ans # Driver Codeif __name__ == '__main__':    # Input    S = "abcabefghijk"     # Function Call    print (findMaxSubsequence(S)) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the length of subsequence// starting with character chstatic int findSubsequence(string S, char ch){         // Length of the string    int N = S.Length;     // Stores the maximum length    int ans = 0;     // Traverse the given string    for(int i = 0; i < N; i++)    {                 // If s[i] is required        // character ch        if (S[i] == ch)        {                         // Increment  ans by 1            ans++;             // Increment  character ch            ch++;        }    }     // Return the current maximum    // length with character ch    return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersstatic int findMaxSubsequence(string S){         // Stores the maximum length of    // consecutive characters    int ans = 0;     for(char ch = 'a'; ch <= 'z'; ch++)    {                 // Update ans        ans = Math.Max(ans, findSubsequence(S, ch));    }     // Return the maximum length of    // subsequence    return ans;} // Driver Codepublic static void Main(){         // Input    string S = "abcabefghijk";     // Function Call    Console.Write(findMaxSubsequence(S));}} // This code is contributed by SURENDRA_GANGWAR
<script>// Javascript program for the above approach // Function to find the length of subsequence// starting with character chfunction findSubsequence(S,ch){    // Length of the string    let N = S.length;          // Stores the maximum length    let ans = 0;      // Traverse the given string    for(let i = 0; i < N; i++)    {                  // If s[i] is required        // character ch        if (S[i] == ch)        {                          // Increment  ans by 1            ans++;              // Increment  character ch            ch=String.fromCharCode(ch.charCodeAt(0)+1);        }    }      // Return the current maximum    // length with character ch    return ans;} // Function to find the maximum length// of subsequence of consecutive// charactersfunction findMaxSubsequence(S){    // Stores the maximum length of    // consecutive characters    let ans = 0;      for(let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++)    {                  // Update ans        ans = Math.max(ans, findSubsequence(S, String.fromCharCode(ch)));    }      // Return the maximum length of    // subsequence    return ans;} // Driver Codelet S = "abcabefghijk";  // Function Calldocument.write(findMaxSubsequence(S));  // This code is contributed by patel2127</script>
7
Time Complexity: O(26*N)Auxiliary Space: O(1)
 
mohit kumar 29
SURENDRA_GANGWAR
unknown2108
shivanisinghss2110
gulshankumarar231
sagartomar9927
subsequence
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
Print all subsequences of a string
sprintf() in C
Convert character array to string in C++
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching