Problem of the day
You are given a string ‘Str’ of length ‘N’. Find the last substring of ‘Str’ in lexicographical order.
In Lexicographical order string ‘S1’ comes before string ‘S2’ if S1 is the prefix of S2 and (|S1| < |S2|), or if none of them is a prefix of the other and at the first position where they differ, the character in ‘S1’ is smaller than the character in ‘S2’.
Example :Consider string ‘Str’ = “abba”, then its substring in lexicographical order is [“a”, “ab”, “abb”, “abba”, “b”, “bb”, “bba”]. Clearly, the last substring in lexicographical order is “bba”.
The first line of input contains an integer ‘T’ denoting the number of test cases, then ‘T’ test cases follow.
The first and only line of each test case consists string ‘Str’
Output format :
For each test case, in a separate line print the last substring of ‘Str’ in lexicographical order.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^4
‘Str’ contains only lowercase English letters.
Time limit: 1 sec
Find all the substring.
Let create an empty string ‘lastSubstr’, and then one by find all the substring of ‘Str’ and compare them with ‘lastSubstr’, if the substring is lexicographically greater than ‘lastSubstr’, then updates ‘lastSubtr’ value to this substring. Note in most of the programming languages operator > or < can be used to compare string lexicographically.
Algorithm
O(N ^ 3), where ‘N’ is the length of string ‘Str’
A string of length ‘N’ has N * (N + 1)/2 substring, i.e number of substrings are in the order of O(N ^ 2), and the time required to compare two substrings of length N, is O(N). Here we are comparing each of the N * (N + 1)/2 substring having a maximum length of ‘N’ with ‘lastSubstr’. Thus, the time complexity will be of the order of O(N ^ 3).
O(N), where ‘N’ is the length of string ‘Str’
The space used by both ‘curSubstr’ and ‘lastSubstr’is of the order of ‘N’. Thus, the space complexity will be O(N).