Alphabetically Greatest Tail of a String
StringsAuto-graded · 24 test casesLast updated
Find the lexicographically greatest suffix of a long lowercase string in linear time by comparing candidate start positions without copying and skipping eliminated blocks.
Greatest Tail of a String
You are given a non-empty string s made only of lowercase English letters. A tail of s is the part of the string from some index i through the end, for any 0 <= i < len(s). The whole string counts as a tail (i = 0).
Return the tail that is largest in dictionary (lexicographic) order.
Ordering rules
- Tails are compared character by character from the left. At the first position where they differ, the tail with the later letter in the alphabet is larger.
- If one tail is a prefix of another, the longer tail is larger. For example,
"ba"is smaller than"baba".
Input
s: a string of lowercase letters.
Output
- A string: the largest tail of
s, as defined above.
Constraints
1 <= len(s) <= 400000scontains only the characters'a'to'z'.- Your solution must be fast enough for the maximum length. Comparing every pair of tails by brute force will be too slow.
Examples
Example 1
Input: greatest_tail('banana')
Output: 'nana'
Example 2
Input: greatest_tail('ababa')
Output: 'baba'
Example 3
Input: greatest_tail('a')
Output: 'a'
Example 4
Input: greatest_tail('aaaaa')
Output: 'aaaaa'
Hints
Hint 1
The answer must begin with the largest letter that occurs in s, so only positions holding that letter are real contenders. Still, many positions can hold it, so you need an efficient way to compare them.
Hint 2
Avoid slicing. Keep two start indices, one for the current best tail and one for a challenger, plus a counter of how many characters the two tails have matched so far. Advance the counter while the characters agree.
Hint 3
When a mismatch shows one tail is larger, a whole block of starting positions (the matched length plus one) can be discarded at once, not just one. Jump past that block so no character is rescanned too often, giving linear time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Comparing all tails directly costs O(n) per comparison and O(n) comparisons, so O(n^2) overall. That is far too slow for n = 400000. Instead we keep three integers and never copy substrings:
best: the start of the best tail found so far.challenger: the start of another tail we are testing against it.matched: how many leading characters the two tails have in common so far.
At each step compare s[best + matched] with s[challenger + matched]:
- Equal: increase
matchedby one. - Best side larger: the challenger loses. So do the starts
challenger + 1 ... challenger + matched, because each of those is a tail that matches a later part of the best tail and then falls below the corresponding position inside it. Move the challenger tochallenger + matched + 1and resetmatched. - Challenger side larger:
bestloses, and so do the startsbest + 1 ... best + matched, by the symmetric argument. The new best ismax(challenger, best + matched + 1), the new challenger is the next index, andmatchedresets to 0.
When challenger + matched reaches n, the challenger ran off the end while still matching. Its tail is then a proper prefix of the best tail, and so are all the starts in that block, so they are all smaller. The best tail is the answer.
Why it is correct
The invariant is that every index below challenger, other than best, has been ruled out, and the first matched characters of the best and challenger tails are equal. Each skip removes only indices that are provably beaten by an index that is already ruled out or is best, so the true maximum is never discarded. The end-of-string case respects the rule that a longer tail beats its own prefix.
Using max(challenger, best + matched + 1) in case 3 (rather than simply challenger) avoids rescanning the same characters. Both give the same answer, but only the max version is linear on inputs like "aaa...ab".
Complexity
- Time:
O(n). The quantitybest + challenger + matchedincreases by at least 1 on every iteration and each term is at mostn, so there are at most about3niterations. - Space:
O(1)extra, plus theO(n)returned slice.
Reference solution
def greatest_tail(s: str) -> str:
n = len(s)
best = 0 # start of the best tail so far
challenger = 1 # start of the tail being compared against it
matched = 0 # number of characters both tails share so far
while challenger + matched < n:
x = s[best + matched]
y = s[challenger + matched]
if x == y:
matched += 1
elif x < y:
# Everything from best to best+matched is beaten by the
# corresponding challenger positions, so skip past it.
best = max(challenger, best + matched + 1)
challenger = best + 1
matched = 0
else:
# The challenger and its next `matched` positions lose.
challenger = challenger + matched + 1
matched = 0
return s[best:]