Lexicographically smallest string which is not a subsequence of given string
Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S.
Input: S = “abcdefghijklmnopqrstuvwxyz”
String “aa” is the lexicographically smallest string which is not present in the given string as a subsequence.
Input: S = “aaaa”
String “aaa” is the lexicographically smallest string which is not present in the given string as a subsequence.
Approach: The idea is to solve the given problem is to find the frequency of the character ‘a’ in the given string (say f). If the value of f is less than the length of the string, then the answer would be the string formed by concatenating ‘a’ f+1 number of times as aaa….(f+1 times) will be the required lexicographically smallest string which is not a subsequence. Otherwise, the answer would be the string formed by concatenating ‘a’ (f-1 times) and ‘b’ at the end of the string.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.