VISUALGO//PROBLEMS
greatest common divisor of strings · array / stringeasy
str1
A
B
C
A
B
C
str2
A
B
C
GCD
·
·
·
ELEMENTS
str1
str2
Python
def gcdOfStrings(str1: str, str2: str) -> str:
# If concatenations don't match, no common divisor
if str1 + str2 != str2 + str1:
return ""
# GCD of lengths gives the answer length
def gcd(a, b):
while b:
a, b = b, a % b
return a
length = gcd(len(str1), len(str2))
return str1[:length]