<p>Given a string <code>s</code>, return <em>the last substring of</em> <code>s</code> <em>in lexicographical order</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;abab&quot;
<strong>Output:</strong> &quot;bab&quot;
<strong>Explanation:</strong> The substrings are [&quot;a&quot;, &quot;ab&quot;, &quot;aba&quot;, &quot;abab&quot;, &quot;b&quot;, &quot;ba&quot;, &quot;bab&quot;]. The lexicographically maximum substring is &quot;bab&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;leetcode&quot;
<strong>Output:</strong> &quot;tcode&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 4 * 10<sup>5</sup></code></li>
	<li><code>s</code> contains only lowercase English letters.</li>
</ul>

class Solution:
    def lastSubstring(self, s: str) -> str:
        # find indices of each last letter (z or whatever). Can do that with monotonic stack or Counter
        # If we iterate over all indices for each substring, that O(n**2)
        # We could use a bijection to guess the length of that 
        # Wait, we know the worst substring ends in last character!! 

        # Preprocessing in O(n): find index of start of longuest block of worst letter
        # then, compare the substrings for all theses index

        worstletter = 'a'
        for c in s:
            if c > worstletter:
                worstletter = c
        
        indices = [] # indices where worstletter starts 
        streak = 0
        maxstreak = 0
        for i, c in enumerate(s):
            if streak and c != worstletter:
                if streak == maxstreak:
                    indices.append(i-streak)
                elif streak > maxstreak:
                    maxstreak = streak
                    indices = [i-streak, ]
                streak = 0
            elif c == worstletter:
                streak += 1
        if streak :
            if streak == maxstreak:
                indices.append(i+1-streak)
            elif streak > maxstreak:
                maxstreak = streak
                indices = [i+1-streak, ]
        dprint("indices", indices)

        out = ""
        for idx in indices:
            cont = s[idx:]
            out = max(cont, out)

        return out
        
def dprint(*args):
    if 0:
        print(*args)
1387