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 Stringsstr1 = "ABCABC"str2 = "ABC"Find largest string that divides both:ABC+ABC="ABCABC" ✓ABC="ABC" ✓GCD String: "ABC"
Understanding the Visualization
1
Input
Two strings str1 and str2
2
Process
Find largest common repeating pattern
3
Output
GCD string or empty if none exists
Key Takeaway
🎯 Key Insight: Two strings have a common divisor if and only if their concatenations are identical: str1 + str2 = str2 + str1
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