Given a string s, find the longest substring that occurs in s at least twice. The occurrences may overlap. Return that substring, or the empty string when no substring occurs twice.
Function Signature
def longest_repeated_substring(s: str) -> str:
Rules
-
A substring is a contiguous, non-empty block of characters of
s
.
-
A substring is repeated when it occurs at two or more different starting positions in
s
. Occurrences may overlap: in
"aaaa"
, the substring
"aaa"
occurs at positions
0
and
1
.
-
Return the longest repeated substring. If several different repeated substrings share the maximum length, return the lexicographically smallest of them (ordinary character-by-character string order).
-
Return
""
when no substring is repeated, that is, when all characters of
s
are different.
Constraints
-
1 <= len(s) <= 3 * 10^4
-
s
consists only of lowercase English letters
a
to
z
.
Examples
Example 1
Input: s = "banana"
Output: "ana"
"ana" occurs at positions 1 and 3; the two occurrences share the middle "a". No substring of length 4 occurs twice.
Example 2
Input: s = "cdcdabab"
Output: "ab"
"cd" and "ab" each occur twice, and no substring of length 3 occurs twice. "ab" is lexicographically smaller than "cd".
Example 3
Input: s = "abcd"
Output: ""
Every character occurs once, so no substring is repeated.