Greatest Common Divisor of Strings Problem
Description
LeetCode Problem 1071.
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.
Solution
Approach: Concatenation Check + GCD of Lengths
If some string x divides both inputs, then str1 is x repeated a times and str2 is x repeated b times. Gluing them together in either order gives x repeated a + b times, so str1 + str2 == str2 + str1. When that test fails, no common divisor exists and the answer is "" (this is what rules out "AAAAAB" and "AAA", even though they share the prefix "A").
When the test passes, the two strings are both built from one shared block, and the longest string that tiles both has length gcd(len(str1), len(str2)): any common divisor's length divides both lengths, and the prefix of that length tiles both strings. So the answer is the prefix of str1 with that length.
For example, "ABABAB" and "ABAB" pass the check, gcd(6, 4) = 2, and the answer is "AB".
Complexity: O(m + n) time for building and comparing the two concatenations, where m and n are the string lengths. O(m + n) extra space for the concatenations.
from math import gcd
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# A common divisor exists only if the order of concatenation does not matter.
if str1 + str2 != str2 + str1:
return ""
return str1[: gcd(len(str1), len(str2))]