Leetcode 1071 - Greatest Common Divisor of Strings
Given two strings str1
and str2
, return the largest string x
such that x
divides both str1
and str2
.
A string x
divides string y
if and only if y
is equal to x
concatenated some number of times. For example, “abc” divides “abcabc” but not “abca”.
str1
and str2
.x
which is the largest string that can divide both str1
and str2
.To solve this problem:
x
divides both str1
and str2
, then it must also divide their concatenations in any order, i.e., x
should divide both str1 + str2
and str2 + str1
.str1 + str2 == str2 + str1
. If not, return an empty string as there’s no common divisor.gcd(len(str1), len(str2))
.import math
def gcd_of_strings(str1, str2):
# Check if str1 + str2 is equal to str2 + str1
if str1 + str2 != str2 + str1:
return ""
# Find the GCD of the lengths of str1 and str2
gcd_length = math.gcd(len(str1), len(str2))
# The GCD string is the substring of str1 from 0 to gcd_length
return str1[:gcd_length]
# Example Usage
str1 = "ABCABC"
str2 = "ABC"
print(gcd_of_strings(str1, str2)) # Output: "ABC"
str1 + str2 == str2 + str1
is (O(len(str1) + len(str2))).Therefore, the overall time complexity is (O(len(str1) + len(str2))).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?