What it teaches: GCD applied to string lengths, after a commutativity check.
Practise it on judges as “Greatest Common Divisor of Strings”.
In plain words
Two words are made by repeating a small tile, like "AB" repeated. If both are built from the same tile, gluing them in either order gives the same result. If they are, the biggest shared tile has a length equal to the greatest common divisor of the two lengths.
Return the biggest tile, or "". Example: str1 = "ABABAB", str2 = "ABAB" → "AB".
The problem
Return the largest string x such that both str1 and str2 are made of repeated copies of x, or "".
These clues point to Number Theory and Combinatorics: GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.
Stuck? Take one hint at a time
Solution · starter
class Solution {
public String gcdOfStrings(String str1, String str2) {
return "";
}
}
Write your solution locally or in your editor for now. Pick Java, Python, C++, JavaScript or Go above: every solution on this page switches with it. The in-browser runner will run these tests right here.
Step 1/3Both orders give the same string, so a common tile exists.
Approach 1
class Solution {
public String gcdOfStrings(String str1, String str2) {
if (!(str1 + str2).equals(str2 + str1)) return "";
return str1.substring(0, gcd(str1.length(), str2.length()));
}
private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}