KatInterview

Alphabetically Greatest Tail of a String

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringsstringstwo-pointersgreedy

Last 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) <= 400000
  • s contains 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.