Last Substring in Lexicographical Order Problem
Description
LeetCode Problem 1163.
Given a string s, return the last substring of s in lexicographical order.
Example 1:
Input: s = "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: s = "leetcode"
Output: "tcode"
Constraints:
1 <= s.length <= 4 * 10^5scontains only lowercase English letters.
Solution
Approach: Two Candidate Starts
First, the answer is always a suffix: if a substring starts at i, extending it to the end of the string only makes it larger (a string is smaller than any longer string that starts with it). So we are looking for the largest suffix.
Comparing all suffixes directly is O(n2), for example on "aaa...ab". Instead we keep two candidate starts: i, the best start so far, and j > i, the one we are testing. k counts how many characters of the two suffixes have matched so far. Compare s[i + k] with s[j + k]:
- Equal: extend the match,
k += 1. s[i + k] < s[j + k]: the suffix atjis larger. More than that, for everytfrom0tok, the suffix ati + tloses to the one atj + t(they match fork - tcharacters, then differ the same way). So none ofi..i+kcan be the answer: jumpitoi + k + 1, resetk = 0, and ificaught up withj, movejtoi + 1.s[i + k] > s[j + k]: by the same argument none ofj..j+kcan win, so jumpjtoj + k + 1and resetk = 0.
Stop when j + k reaches the end of the string. At that point the suffix at j is a prefix of the one at i, so it is smaller, and s[i:] is the answer.
Every comparison either grows k or moves i or j past all the matched characters, which keeps the total work linear.
Complexity: O(n) time and O(1) extra space (besides the returned substring).
class Solution:
def lastSubstring(self, s: str) -> str:
# The answer is a suffix. i: start of the best suffix so far, j: the challenger,
# k: how many characters of the two already matched.
i, j, k = 0, 1, 0
n = len(s)
while j + k < n:
if s[i + k] == s[j + k]:
k += 1
elif s[i + k] < s[j + k]:
# The suffix at j wins, and so does the one at j + t over the one at i + t for t <= k:
# no start in i..i+k can be the answer.
i += k + 1
k = 0
if i >= j:
j = i + 1
else:
# The suffix at i wins: starts j..j+k are out for the same reason.
j += k + 1
k = 0
return s[i:]