SDE & MLE Prep

1071. Greatest Common Divisor of Strings

Problem

String t divides s if s is t repeated one or more times. Return the longest string that divides both str1 and str2, or "" if none does.

Example: "ABCABC", "ABC" → "ABC"; "ABABAB", "ABAB" → "AB"; "LEET", "CODE" → ""

If some string x divides both, then str1 + str2 == str2 + str1 (both are repetitions of x); conversely, when that holds both are repetitions of a common block, and the longest divisor has length gcd(len1, len2).

Complexity: O(n + m).

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if str1 + str2 != str2 + str1:
            return ""
        return str1[:math.gcd(len(str1), len(str2))]