Example 1
- Input
- str1 = "ABCABC", str2 = "ABC"
- Output
- "ABC"
Concatenations both equal ABCABCABC. Length gcd(6,3)=3 gives prefix ABC.
Return the longest string whose repetitions form both input strings. Check compatibility before applying Euclidean GCD to their lengths.
A nonempty string x divides a string s when s consists of one or more copies of x. Given str1 and str2, return the longest string dividing both, or the empty string if none exists. The official exercise uses uppercase English letters.
1 <= str1.length, str2.length <= 1000.Concatenations both equal ABCABCABC. Length gcd(6,3)=3 gives prefix ABC.
Both are copies of AB. Euclid computes gcd(6,4)=gcd(4,2)=2, so a four-character prefix is too long.
BLUECODE differs from CODEBLUE. Equal lengths alone do not imply a common divisor string.
The one-character strings commute and their length GCD is one.
A common repeating block makes str1+str2 and str2+str1 identical. If concatenation order changes the characters, no common block exists, even when the lengths share a divisor. Once compatibility is established, the longest block has length gcd(m,n). In Example 1, ABCABC and ABC commute, their lengths are 6 and 3, and the length GCD is 3, so return ABC.
Reveal Euclidean GCD: intuition, complexity, and code
Separate structural compatibility from numeric size. Euclid works because subtracting multiples preserves the set of common divisors, while remainders make progress.