Problem
For two strings s
and t
, we say “t
divides s
” if and only if s = 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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Run the gcd
To solve the problem of finding the largest string x
such that x
divides both str1
and str2
, we can employ the greatest common divisor (GCD) concept:
- Check Divisibility:
- We need to check if a substring
x
can repeatedly form bothstr1
andstr2
.
- We need to check if a substring
- GCD of Lengths:
- The length of the largest
x
that can divide bothstr1
andstr2
will be the greatest common divisor (GCD) of their lengths. This follows from the property of GCD in number theory.
- The length of the largest
- Construct and Verify:
- Construct the substring
x
using the firstGCD(len(str1), len(str2))
characters of either string. - Verify if this substring can repeatedly form both
str1
andstr2
.
- Construct the substring
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m + gcd(n, m))
, wheren
andm
are the lengths ofstr1
andstr2
respectively. This accounts for computing the GCD and verifying the constructed substring. - 🧺 Space complexity:
O(gcd(n, m))
, for storing the resulting substring.