Greatest Common Divisor of Strings - Problem

For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Input & Output

Example 1 — Basic Case
$ Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
💡 Note: "ABC" divides "ABCABC" (ABC + ABC) and divides "ABC" (ABC × 1). This is the largest such string.
Example 2 — No Common Divisor
$ Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
💡 Note: "AB" can build both: "ABABAB" = AB + AB + AB and "ABAB" = AB + AB
Example 3 — No Common Pattern
$ Input: str1 = "LEET", str2 = "CODE"
Output: ""
💡 Note: No string can divide both "LEET" and "CODE" since they share no common repeating pattern

Constraints

  • 1 ≤ str1.length, str2.length ≤ 1000
  • str1 and str2 consist of English uppercase letters

Visualization

Tap to expand
Greatest Common Divisor of Strings INPUT str1 = "ABCABC" A B C A B C str2 = "ABC" A B C String Division: "ABC" divides "ABCABC" because: "ABC" + "ABC" = "ABCABC" "ABC" divides "ABC" because: "ABC" x 1 = "ABC" ALGORITHM STEPS 1 Check Validity str1 + str2 == str2 + str1? "ABCABCABC" == "ABCABCABC" OK - Valid! 2 Find GCD of Lengths len(str1) = 6 len(str2) = 3 GCD(6, 3) = 3 3 Euclidean Algorithm GCD(6,3): 6 mod 3 = 0 GCD(3,0): return 3 4 Extract Result Take first GCD chars str1[0:3] = "ABC" Time: O(m+n), Space: O(m+n) FINAL RESULT Greatest Common Divisor: "ABC" Verification: str1 check: "ABC" x 2 = "ABCABC" OK str2 check: "ABC" x 1 = "ABC" OK Output: "ABC" Key Insight: If str1 + str2 equals str2 + str1, a GCD string exists. The GCD string length equals GCD(len(str1), len(str2)). This works because string divisibility mirrors integer divisibility. The concatenation check ensures both strings are built from the same repeating pattern. TutorialsPoint - Greatest Common Divisor of Strings | Optimal Solution (GCD Approach)
Asked in
Google 15 Amazon 12 Facebook 8
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen