Last Substring In Lexicographical Order

Hard
0/120
Average time to solve is 45m
profile
Contributed by
5 upvotes
Asked in companies
Goldman SachsSalesforce

Problem statement

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”. 
Detailed explanation ( Input/output format, Notes, Images )
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
Hint

Find all the substring.

Approaches (3)
Brute Force

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’.
Time Complexity

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).

Space Complexity

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).

Code Solution
(100% EXP penalty)
Last Substring In Lexicographical Order
Full screen
Console