Last Substring In Lexicographical Order

Posted: 24 Feb, 2021
Difficulty: Hard

PROBLEM STATEMENT

Try Problem

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”. 
Input format :
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.
Constraints :
1 <= T <= 50
1 <= N <= 10^4
‘Str’ contains only lowercase English letters.

Time limit: 1 sec
Approach 1

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

 

  • Create an empty string ‘lastSubstr’.
  • Run a loop where ‘i’ ranges from 0 to N-1 and for each ‘i’ do the following
    • Create an empty string ‘curSubstr’.
    • Run a loop where ‘j’ ranges from ‘i’ to N - 1 and for each ‘j’ -:
      • Append the jth character of Str at the end of curSubstr’
      • If  curSubstr’  > ‘lastSubstr’, then do lastSubstr := curSubstr. 
  • Return lastSubstr’.
Try Problem