problems / 167

Repeating Alice's Banner

medium strings string-matching 1000 ms · 256 MB

Repeating Alice's Banner

Alice has a stencil with the word A on it, and she is painting a long fence with it: she paints A, then another copy of A right after it, then another, always end to end with no gaps. Bob is walking along the fence looking for his favourite phrase B. He is happy as soon as B shows up somewhere on the fence as a block of consecutive letters, even if it starts in the middle of one copy and ends inside a later one. Alice doesn't want to waste paint. What is the smallest number of copies she has to paint to make Bob happy?

Formally, let A^k be the string made by writing A exactly k times in a row. Find the smallest integer k ≥ 1 such that B is a substring (a contiguous block of characters) of A^k, or report that no such k exists.

Input

The first line contains the string A (1 ≤ |A| ≤ 10^6).

The second line contains the string B (1 ≤ |B| ≤ 10^6).

Both strings consist of lowercase English letters only.

Output

Print one integer: the smallest k ≥ 1 such that B is a substring of A^k, or -1 if B is not a substring of A^k for any k.

Notes

In the first example, A^1 = abcd does not contain cdabcda, but A^3 = abcdabcdabcd does (starting at the third letter). A^2 = abcdabcd has eight letters but does not contain cdabcda.

In the second example, every copy of A is followed by an a again, so ab followed by b never appears, no matter how many copies Alice paints.

Example 1

Input

abcd
cdabcda

Output

3

Example 2

Input

ab
abb

Output

-1

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

Hint 1

Since A repeats forever, any occurrence of B can be shifted left by whole copies of A. So where does the earliest possible start of B have to lie, and how far must the copies extend to cover B's end?

Hint 2

Find the first occurrence of B in the repeated text with a linear-time matching method such as KMP, using only about |B| / |A| + 2 copies of A. Then count how many copies are needed to reach the end of that occurrence.

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

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