problems / 243

Greatest Common Divisor of Strings

easy strings math gcd 1000 ms · 256 MB

Greatest Common Divisor of Strings

A string t divides a string s if s is t written one or more times in a row. For example, ab divides ababab, and abc divides abc, but ab does not divide aba.

You are given T pairs of strings (a, b). For each pair, find the longest string that divides both a and b.

Input

The first line contains T (1 ≤ T ≤ 10^5), the number of pairs.

Each of the next T lines contains two strings a and b separated by a single space. Both consist of lowercase English letters and have length at least 1.

The total length of all strings in the input is at most 10^6.

Output

For each pair, print one line: the longest string that divides both a and b, or -1 if no string divides both.

Notes

In the first example, ab divides both ababab and abab. abab is longer, but it does not divide ababab. In the pair abab abba, the only string that divides abba is abba itself, and it does not divide abab, so the answer is -1.

In the second example, the single letter a divides a (one copy), and xyzxyz is written once in the first string and twice in the second.

Example 1

Input

5
ababab abab
abcabc abc
leet code
aaaa aa
abab abba

Output

ab
abc
-1
aa
-1

Example 2

Input

3
a a
xyzxyz xyzxyzxyzxyz
ba ab

Output

a
xyzxyz
-1

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

Hint 1

If t divides both a and b, its length must divide both |a| and |b|. What does that say about the longest possible length?

Hint 2

If a = t^p and b = t^q, then a + b and b + a are the same string. Check whether that one comparison is enough to tell if any common divisor exists.

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

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