LeetCode: Last Substring in Lexicographical Order Posted on August 5, 2019July 26, 2020 by braindenny Last Substring in Lexicographical Order Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #string, #greedy, #twopointer Given a string s, return the last substring of s in lexicographical order. Example 1: Input: "abab" Output: "bab" Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab". Example 2: Input: "leetcode" Output: "tcode" Note: 1 <= s.length <= 4 * 10^5 s contains only lowercase English letters. Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: // https://code.dennyzhang.com/last-substring-in-lexicographical-order // Basic Ideas: greedy + two pointer // // The ending point of the result is the last character. // Need to define where is the starting point. // Apparently we know the value of the starting point. // It must be the biggest character in the string. // // Use two slow and fast pointer: // - slow: starting point of the result // - fast: starting point of the candidate // // The key part is slow pointer won't need to move back // // If candidate of faster pointer is better than the slow pointer, // just need to move the slow pointer to faster point. // // No need to examining starting in between slow and fast characters! // // cabcabcb // . . . // // // Complexity: Time O(n), Space O(1) func max(x, y int) int { if x>y { return x } else { return y } } func lastSubstring(s string) string { i, j := 0, 1 for k:=0; k+j<len(s); { if s[i+k] == s[j+k] { k++ continue } if s[i+k] > s[j+k] { j = j+k+1 } else { // Think: why not simply i=j i = max(i+k+1, j) j = i+1 } k = 0 } return s[i:] } Post Views: 0