Longest Repeated Substring

medium string-matching binary-search hashing 2250 ms · 256 MB

Longest Repeated Substring

You are given a string s of lowercase English letters. Find the longest substring of s that occurs at least twice. The two occurrences are allowed to overlap.

If several substrings share the longest length, output the one whose first (leftmost) occurrence starts earliest in s. If no substring occurs twice (all characters are distinct), there is no answer.

Input

The first line contains the string s (1 ≤ |s| ≤ 2·10^5), consisting only of lowercase English letters.

Output

If some substring occurs at least twice, print two lines: the length of the longest such substring, and then the substring itself (the one whose leftmost occurrence starts earliest among all substrings achieving that length).

If no substring occurs twice, print a single line containing 0.

Notes

In the first example, s = banana. The substring ana occurs at positions 1 and 3 (0-indexed), overlapping in the middle a, and no longer substring repeats, so the answer is 3 and ana.

In the second example every character of s is distinct, so the answer is 0.

Example 1

Input

banana

Output

3
ana

Example 2

Input

abcde

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

If a substring of length L occurs twice, does a shorter substring also occur twice? What does that suggest about searching over the possible answer lengths?

Hint 2

For a fixed length, you can check whether some window of that length appears twice by comparing window fingerprints, such as polynomial hashes, computed in constant time per window. Combine this check with a binary search over the length.

Hint 3

Once you know the best length, record the first occurrence of each window's fingerprint as you scan left to right, and among windows that appear more than once take the smallest first occurrence. Use two independent hashes so that adversarial inputs cannot cause false matches.

report an issue Prefer your own editor? sooks prep 66 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.