Home
DSA Patterns
Two Pointers
Greatest Common Divisor of Strings
Greatest Common Divisor of Strings (LeetCode 1071)
Greatest Common Divisor of Strings (LeetCode 1071): find the largest string that divides both inputs: compare str1 + str2 with str2 + str1, then take the prefix whose length is the gcd of the two lengths.
Problem Understanding
Greatest Common Divisor of Strings (LeetCode 1071): a string t divides a string s when s is t written one or more times in a row. Given str1 and str2, return the largest string x that divides both, or "" if there is none.
Examples: "ABCABC", "ABC" → "ABC"; "ABABAB", "ABAB" → "AB"; "LEET", "CODE" → "".
The Intuition: Strings That Commute Share a Block
If both strings are made of the same block x, the order you glue them in does not matter: str1 + str2 and str2 + str1 are both just x repeated. If they are not, the two glued strings differ somewhere.
- Compare
str1 + str2withstr2 + str1. If they differ, return"". - Find the block length. Every divisor's length divides both lengths, so the longest one is
gcd(len1, len2), found with Euclid's algorithm. - Return that many letters from the front of
str1.
The comparison is one index walking two strings side by side, the same move as Merge Strings Alternately. Repeated String Match is another problem about one string built from repeats of another.
Greatest Common Divisor of Strings Visualization
OUTLINED = FROM STR1 · TINTED = FROM STR2
A + B == B + A?
str1 + str2
0
1
2
3
4
5
6
7
8
9
str2 + str1
0
1
2
3
4
5
6
7
8
9
a
:
b
:
Answer
:
str1 + str2 = str2 + str1 = "ABABABABAB": both are repeats of one block
Next
The block's length is gcd(6, 4). Start Euclid with a = 6, b = 4
str1
str2
The top two rows are the two concatenations, with each letter coloured by the string it came from. The compare step paints where they agree green and the first difference red. After Euclid, the bottom rows cut both strings into blocks of the gcd length. Try Example 3, which fails at the first letter, and Late mismatch, which only fails at index 3.
Greatest Common Divisor of Strings Dry Run
Input: str1 = "ABABAB", str2 = "ABAB".
str1 + str2 = "ABABABABAB" and str2 + str1 = "ABABABABAB" are equal, so a divisor exists. Euclid on the lengths 6 and 4:
| Round | a | b | a % b |
|---|---|---|---|
| start | 6 | 4 | 2 |
| 1 | 4 | 2 | 0 |
| 2 | 2 | 0 | (stop) |
Answer: gcd = 2, so the first 2 letters of str1: "AB".
Greatest Common Divisor of Strings LeetCode Solution
One comparison of the two concatenations, then Euclid on the lengths. Python can use math.gcd and C++ std::gcd instead of the loop.
Greatest Common Divisor of Strings Code
1var gcdOfStrings = function(str1, str2) {2 if (str1 + str2 !== str2 + str1) {3 return "";4 }5 let a = str1.length, b = str2.length;6 while (b !== 0) {7 [a, b] = [b, a % b];8 }9 return str1.slice(0, a);10};
Greatest Common Divisor of Strings in Python, Java, C++, TypeScript and C
Greatest Common Divisor of Strings in Python
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1 + str2 != str2 + str1:
return ""
a, b = len(str1), len(str2)
while b:
a, b = b, a % b
return str1[:a]Greatest Common Divisor of Strings in Java
class Solution {
public String gcdOfStrings(String str1, String str2) {
if (!(str1 + str2).equals(str2 + str1)) {
return "";
}
int a = str1.length(), b = str2.length();
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return str1.substring(0, a);
}
}Greatest Common Divisor of Strings in C++
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if (str1 + str2 != str2 + str1) {
return "";
}
int a = str1.size(), b = str2.size();
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return str1.substr(0, a);
}
};Greatest Common Divisor of Strings in TypeScript
function gcdOfStrings(str1: string, str2: string): string {
if (str1 + str2 !== str2 + str1) {
return "";
}
let a = str1.length, b = str2.length;
while (b !== 0) {
[a, b] = [b, a % b];
}
return str1.slice(0, a);
}Greatest Common Divisor of Strings in C
char* gcdOfStrings(char* str1, char* str2) {
int m = strlen(str1), n = strlen(str2);
char* ab = malloc(m + n + 1);
char* ba = malloc(m + n + 1);
sprintf(ab, "%s%s", str1, str2);
sprintf(ba, "%s%s", str2, str1);
int same = strcmp(ab, ba) == 0;
free(ab);
free(ba);
if (!same) {
return calloc(1, 1);
}
int a = m, b = n;
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
char* out = malloc(a + 1);
memcpy(out, str1, a);
out[a] = '\0';
return out;
}Edge Cases & Common Mistakes
- Taking the shorter string as the answer:
"AAAAAA","AAAA"gives"AA", not"AAAA", because 4 does not divide 6. - Checking only that one string starts with the other:
"ABAB","ABA"passes that check, but the concatenations differ at index 3, so the answer is"". - Equal strings: the answer is the whole string.
- A length that divides both is not enough:
"LEET","CODE"both have length 4, but nothing divides them.
Summary
If str1 + str2 != str2 + str1, return "". Otherwise return the first gcd(len(str1), len(str2)) letters of str1. O(m + n) time for the comparison, O(m + n) space for the two concatenations.
More practice: DSA interview questions with answers · patterns cheat sheet
