1071. Greatest Common Divisor of Strings
Description
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.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Example 4:
Input: str1 = "AAAAAB", str2 = "AAA"
Output: ""
Constraints:
1 <= str1.length, str2.length <= 1000str1andstr2consist of English uppercase letters.
Solutions
Solution 1: Enumeration
Thinking
A common divisor string must tile both inputs, so its length divides both lengths. Trying prefixes from the shorter length downward is enough for \(m,n\le 1000\).
Each candidate \(t=\textit{str1}[:i]\) is repeated until it matches the target length and compared.
The first \(t\) that tiles both strings is the longest; otherwise the answer is empty.
Enumerate candidate prefixes \(t\) from the shorter string length downward, and check whether repeating \(t\) can produce \(\textit{str1}\) and \(\textit{str2}\). The first valid \(t\) is the longest gcd string.
The time complexity is \(O((m + n) \times \min(m, n))\), and the space complexity is \(O(m + n)\), where \(m\) and \(n\) are the lengths of the two strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Solution 2: Math
Thinking
Enumeration still tries many lengths. If a common divisor exists then \(s_1+s_2=s_2+s_1\), and the longest length is \(\gcd(|s_1|,|s_2|)\).
We reject unequal concatenations and otherwise return the prefix of \(s_1\) of that gcd length.
If a gcd string exists, then \(s_1+s_2=s_2+s_1\). In that case the length of the longest gcd string is \(\gcd(|s_1|,|s_2|)\).
The time complexity is \(O(m + n)\), and the space complexity is \(O(m + n)\), where \(m\) and \(n\) are the lengths of the two strings.
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |