1214. Shortest Stencil

A sign painter owns one stencil and stamps it repeatedly along a banner so that the stamps may overlap but must leave no gap. The banner text is the lowercase string s. A stencil is a string t that is stamped at some positions of s where the text matches t exactly; the stamps must together cover every position of s. The stencil may be as long as s itself, and that always works.

Return the length of the shortest stencil that can cover s. Such a stencil must be a prefix and also a suffix of s, which points to the prefix function and a left-to-right pass that tracks the furthest stamp end. The intended solution runs in O(n) time and O(n) space.

Example 1

Input:
s = "abaabaaba"
Output:
3
Explanation:

The stencil aba matches at positions 0, 3 and 6 and covers all nine letters; no shorter one works, so the answer is 3.

Example 2

Input:
s = "abab"
Output:
2
Explanation:

The stencil ab matches at positions 0 and 2 and covers everything, so the answer is 2.

Example 3

Input:
s = "abcd"
Output:
4
Explanation:

No proper prefix is also a suffix, so the whole string is needed and the answer is 4.

Constraints

1 ≤ s.length ≤ 2 * 105

s contains only lowercase letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…