Bob's Hidden Password
Alice invented a game: she writes down a long string s and claims that a password is buried
inside it. According to her rules, a string t qualifies as a password of s if
tis a prefix ofs,tis also a suffix ofs, andtoccurs somewhere else instoo — at an occurrence that neither starts at the very first character ofsnor ends at the very last character ofs.
(The second and third conditions can be satisfied by the same occurrence: t just has to show up
at least once strictly inside s, away from both ends.) Alice always picks the longest string
that qualifies, and bets Bob he can't find a longer one. Bob suspects that sometimes no non-empty
string qualifies at all — in which case he calls Alice's password "just a legend" and refuses to
play.
Help Bob find the password, or confirm that it doesn't exist.
Formally, s has length n. Among all non-empty strings t with |t| < n such that t is a
prefix of s, t is a suffix of s, and there exist indices 1 ≤ i ≤ j ≤ n with i > 1,
j < n, j - i + 1 = |t|, and s[i..j] = t, find one of maximum length. (Note |t| < n is
automatic: a password can't be the whole string, since then it would have nowhere strictly inside
to hide.)
Input
The first line contains the integer n (1 ≤ n ≤ 10^6).
The second line contains the string s, of length n, consisting of lowercase English letters.
Output
Print the longest password of s, or Just a legend if no non-empty string satisfies all three
conditions.
Notes
In the first example, s = ababab. The string abab is a prefix and a suffix, but its only other
possible occurrence would have to end at the last character, so it doesn't count. The shorter
border ab does occur strictly inside, starting at the third character, so it is the answer.
In the second example every letter of s is distinct, so the only common prefix/suffix is the
empty string, and the answer is Just a legend.
In the third example, s = aabaa. The border aa is a prefix and a suffix, but its only two
occurrences are the prefix itself and the suffix itself — neither is strictly inside. The shorter
border a does occur strictly inside (the third character), so it is the answer.