Skip to content
AI360Xpert
Beta
Difficulty: EasyMath & Geometry

Greatest Common Divisor of Strings

Problem in Plain English

Return the longest string whose repetitions form both input strings. Check compatibility before applying Euclidean GCD to their lengths.

Problem Statement

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.

Constraints

  • 1 <= str1.length, str2.length <= 1000.
  • Each string contains only uppercase English letters.

Examples

Example 1

Input
str1 = "ABCABC", str2 = "ABC"
Output
"ABC"

Concatenations both equal ABCABCABC. Length gcd(6,3)=3 gives prefix ABC.

Example 2

Input
str1 = "ABABAB", str2 = "ABAB"
Output
"AB"

Both are copies of AB. Euclid computes gcd(6,4)=gcd(4,2)=2, so a four-character prefix is too long.

Example 3

Input
str1 = "BLUE", str2 = "CODE"
Output
""

BLUECODE differs from CODEBLUE. Equal lengths alone do not imply a common divisor string.

Example 4

Input
str1 = "A", str2 = "A"
Output
"A"

The one-character strings commute and their length GCD is one.

Intuition

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.

Approaches

Euclidean GCD

Optimal

Solution Details

Reveal Euclidean GCD: intuition, complexity, and code

Hints

Hint 1
A common repeating word makes concatenation order irrelevant.
Hint 2
After verifying that order check, a divisor word’s length must divide both lengths.
Hint 3
Compute the length GCD with (a,b)→(b,a mod b), then return that many prefix characters.

Edge Cases

  • Equal lengths but different contents must return empty.
  • Identical strings return the whole string, even if it has a shorter primitive period.
  • Length GCD one does not bypass the compatibility check.

Common Mistakes and Interview Tips

  • Returning a gcd-length prefix without checking content fails BLUE and CODE.
  • Using substring containment instead of exact repetitions permits partial trailing copies.
  • Overwriting a before calculating a mod b corrupts the Euclidean transition.

Key Takeaway

Separate structural compatibility from numeric size. Euclid works because subtracting multiples preserves the set of common divisors, while remainders make progress.