problems / 214

Suki's Scent Trail

medium suffix-structures string-matching 3000 ms · 256 MB

Suki's Scent Trail

Suki, a curly-coated dog with a grey beard and white paws, loves following scent trails through the park. Today, she's tracking a winding path marked by another dog's scent—a long string of smells. She wants to identify the oldest part of the trail she can re-recognize by matching the end of the trail against earlier segments. The older the part she can match, the longer she's been following this trail.

You are given a scent trail represented as a string. Find the length of the longest suffix of this string that also appears entirely within the part of the string before it.

Input

The first line contains n (1 ≤ n ≤ 2·10^5), the length of the scent trail.

The second line contains a string s of length n consisting of lowercase English letters.

Output

Print the length of the longest suffix of s that appears at least once as a substring in s[0:n-k] where k is the length of that suffix. If no suffix appears earlier in the string, print 0.

Notes

A suffix of length k is the substring s[n-k:n]. For this suffix to count, it must appear at least once in the first n-k characters of the string.

In the first example, the string is "abcab". The suffix "ab" (length 2) appears at position 0 in the prefix "abc", so the answer is 2. The longer suffix "cab" does not appear earlier, and neither do longer suffixes.

Example 1

Input

5
abcab

Output

2

Example 2

Input

6
banana

Output

2

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

Hint 1

Suppose a suffix of length k occurs earlier in the string. Must a shorter suffix also occur earlier? What does that tell you about searching over lengths?

Hint 2

With n up to 2·10^5, testing every length against the whole prefix is too slow. For a fixed length k, ask whether some window of length k lying entirely inside s[0:n-k] equals the suffix. Each such test should take about linear time.

Hint 3

Binary search on k, and for each k compare the hash of the suffix with the hashes of all length-k windows in the prefix. Use a hash that is hard to collide, such as a polynomial hash modulo the prime 2^61−1 (or two large primes) with a random base. Plain unsigned overflow mod 2^64 can be broken by the tests.

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

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