Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1.
Input: S = “acbbebcg”
Explanation: The longest subsequence of required type is “cbbbc”, whose length is 5.
The difference between largest (‘c’) and smallest (‘b’) ASCII values is c – b = 99 – 98 = 1, which is minimum possible.
Input: S = “abcd”
Explanation: The longest subsequence of the required type is “ab”, whose length is 2. Other possible subsequences are “bc” and “cd”.
The difference between largest(‘b’) and smallest(‘a’) ASCII values is b – a = 98 – 97 = 1.
Naive Approach: The simplest approach to solve the problem is to generate all possible subsequences of the given string S and print the length of the subsequence which is of maximum length and having a difference between ASCII values of the largest and smallest character is exactly equal to 1.
Time Complexity: O(N * 2N)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the main idea is to use a Map to optimize the above approach. Follow the steps below to solve the problem:
- Initialize a variable, say maxLength, that stores the maximum length of the resultant subsequence.
- Store the frequency of characters in a Map, say M.
- Traverse the string and for each character, say ch, check if there exists character c with ASCII value (ch – 1) in the map M or not. If found to be true, then update maxLength as the maximum of maxLength and (M[ch] + M[ch – 1]).
- After completing the above steps, print the value of maxLength as the result.
Below is the implementation of the above approach:
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.