Given a string str containing lowercase characters, the task is to find the lexicographically largest sub-sequence of str.
Input: str = “abc”
All possible sub-sequences are “a”, “ab”, “ac”, “b”, “bc” and “c”
and “c” is the largest among them (lexicographically)
Input: str = “geeksforgeeks”
Approach: Let mx be the lexicographically largest character in the string. Since we want the lexicographically largest sub-sequence we should include all occurrences of mx. Now after all the occurrences have been used, the same process can be repeated for the remaining string (i.e. sub-string after the last occurrence of mx) and so on until the there are no more characters left.
Below is the implementation of the above approach:
# Python 3 implementation of the approach
# Function to return the lexicographically
# largest sub-sequence of s
def getSubSeq(s, n):
res = “”
cr = 0
while (cr < n): # Get the max character from # the string mx = s[cr] for i in range(cr + 1, n): mx = max(mx, s[i]) lst = cr # Use all the occurrences of the # current maximum character for i in range(cr,n): if (s[i] == mx): res += s[i] lst = i # Repeat the steps for the # remaining string cr = lst + 1 return res # Driver code if __name__ == '__main__': s = "geeksforgeeks" n = len(s) print(getSubSeq(s, n)) # This code is contributed by # Surendra_Gangwar [tabby title="C#"]
Time Complexity: O(N) where N is the length of the string.
- Find the lexicographically largest palindromic Subsequence of a String
- Lexicographically largest subsequence such that every character occurs at least k times
- Lexicographically largest string formed from the characters in range L and R
- Lexicographically smallest and largest substring of size k
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically next string
- Lexicographically middle string
- Lexicographically n-th permutation of a string
- Lexicographically first palindromic string
- Lexicographically minimum string rotation | Set 1
- Lexicographically next greater string using same character set
- Find n-th lexicographically permutation of a string | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.