Problem Description
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. A string t divides another string s if s can be constructed by concatenating one or more copies of t.
Key Insights
- The necessary condition for a common divisor string is that str1 + str2 must equal str2 + str1.
- The length of the candidate divisor string must be a divisor of both string lengths.
- Using the greatest common divisor (gcd) of the lengths of str1 and str2 gives the length of the largest possible candidate.
- Once a candidate is found, it can be verified by checking if repeating it forms the original strings.
Space and Time Complexity
Time Complexity: O(n + m), where n and m are the lengths of str1 and str2 respectively. Space Complexity: O(n + m), primarily for storage of the input strings and the resulting substring.
Solution
The solution first checks if str1 + str2 equals str2 + str1; if not, no common divisor exists and an empty string is returned. Otherwise, the algorithm computes the gcd of the lengths of str1 and str2. The substring of str1 up to this gcd length is the common divisor string since repeating it forms both str1 and str2.