← All problems

2. Greatest Common Divisor of Strings

EasyArray / StringOriginal on LeetCode ↗

Say a string t divides a string s when s is just t written one or more times back to back (for example "xy" divides "xyxyxy").

Given str1 and str2, return the longest string that divides both of them. If no string divides both, return an empty string.

Constraints

  • 1 <= len(str1), len(str2) <= 1000
  • Both strings contain only uppercase or lowercase English letters.

Examples

Example 1
Input:  str1 = "XYXYXY", str2 = "XYXY"
Output: "XY"
Example 2
Input:  str1 = "AAA", str2 = "AA"
Output: "A"
Example 3
Input:  str1 = "CODE", str2 = "DOGS"
Output: ""

Hints

Hint 1

If a common divisor exists, then str1 + str2 must equal str2 + str1.

Hint 2

When it does, the longest divisor has length gcd(len(str1), len(str2)).

Python 3

Run checks the examples · Submit checks every test. The first run downloads Python (about 10 MB) and takes a few seconds.