problems / 186

The Canyon Echo

easy palindromes string-matching 1000 ms · 256 MB

The Canyon Echo

A canyon has a peculiar property: when you shout a word, it echoes back the first part of your word reversed. For instance, if you shout "abaca", the canyon echoes back "acaba" (the reverse of "abaca").

However, there's a magical point where the echo is perfectly symmetric: when the initial segment of your word is palindromic (reads the same forwards and backwards), the echo pattern becomes symmetric and beautiful.

Given a word, find the length of the longest initial segment (prefix) that forms a palindrome.

Input

The first line contains n (1 ≤ n ≤ 10^5), the length of the word. The second line contains a string s of length n consisting of lowercase letters.

Output

Print the length of the longest prefix of s that is a palindrome.

Notes

A palindrome reads the same forwards and backwards. Every single character is a palindrome by itself.

In the first example, the word is "abaca". The palindromic prefixes are "a" (length 1) and "aba" (length 3), so the answer is 3.

Example 1

Input

5
abaca

Output

3

Example 2

Input

5
abcba

Output

5

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

Hint 1

Consider each prefix on its own: is it a palindrome? Why would checking every prefix with a full comparison be too slow for a string of 10^5 identical letters?

Hint 2

The prefix function of KMP finds the longest proper prefix that is also a suffix in linear time. Build a string from s, a separator that cannot appear in s, and reverse(s), then ask what the last value means for the prefixes of s.

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

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