Given a string s, you need to find and return the lexicographically largest substring among all possible substrings of s.
In lexicographical order, strings are compared character by character from left to right. For example, "zzb" comes after "zza" because at the third position, 'b' > 'a'. The last substring in lexicographical order is the one that would appear at the end if all substrings were sorted alphabetically.
Example: For string "abab", all substrings are: ["a", "ab", "aba", "abab", "b", "ba", "bab", "a", "ab", "b"]. After removing duplicates and sorting: ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically largest is "bab".
Key Insight: The optimal substring must start with the largest character in the string, and we need to find the best starting position among all occurrences of this maximum character.
Input & Output
Visualization
Time & Space Complexity
O(n²) to generate all substrings, O(n) to compare each substring lexicographically
Space to store all substrings (there are O(n²) substrings, each of average length O(n))
Constraints
- 1 ⤠s.length ⤠4 à 105
- s contains only lowercase English letters
- Follow-up: Can you solve this in O(n) time complexity?