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
xcan repeatedly form bothstr1andstr2.
- We need to check if a substring
- GCD of Lengths:
- The length of the largest
xthat can divide bothstr1andstr2will 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
xusing the firstGCD(len(str1), len(str2))characters of either string. - Verify if this substring can repeatedly form both
str1andstr2.
- Construct the substring
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + m + gcd(n, m)), wherenandmare the lengths ofstr1andstr2respectively. This accounts for computing the GCD and verifying the constructed substring. - 🧺 Space complexity:
O(gcd(n, m)), for storing the resulting substring.