Browse curriculum

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.

  1. Compare str1 + str2 with str2 + str1. If they differ, return "".
  2. Find the block length. Every divisor's length divides both lengths, so the longest one is gcd(len1, len2), found with Euclid's algorithm.
  3. 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

A

0

B

1

A

2

B

3

A

4

B

5

A

6

B

7

A

8

B

9

str2 + str1

A

0

B

1

A

2

B

3

A

4

B

5

A

6

B

7

A

8

B

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

Free preview: the first 3 of 5 steps

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

The approach, step by step

  1. Compare the concatenations

    If str1 + str2 differs from str2 + str1, return the empty string.

  2. Take the gcd of the lengths

    Run Euclid on len(str1) and len(str2): replace (a, b) with (b, a % b) until b is 0.

  3. Return the prefix

    The answer is the first gcd letters of str1.

Frequently asked questions

Why does str1 + str2 == str2 + str1 prove a common divisor exists?

Two strings that give the same result in either order are both repeats of one shorter block; this is a known result about words that commute. If some string x divides both, str1 = x repeated p times and str2 = x repeated q times, so both concatenations are x repeated p + q times and are equal. If the concatenations differ, no such x can exist.


Why is the answer the prefix of length gcd(len1, len2)?

Once both strings are repeats of a block, any divisor has to be a whole number of blocks, and its length must divide both lengths. The longest length that divides both is their greatest common divisor, and the divisor of that length is simply the first gcd(len1, len2) letters of str1.


Is there a brute-force approach?

Yes: try every length L from min(len1, len2) down to 1, skip it unless L divides both lengths, and check whether the first L letters repeat into both strings. It is O(min(m, n) · (m + n)) in the worst case. The concatenation test does the same job in one O(m + n) comparison.


What is Euclid’s algorithm doing here?

It finds gcd(a, b) by replacing the pair (a, b) with (b, a % b) until b is 0; then a is the gcd. For lengths 6 and 4 it goes (6, 4) → (4, 2) → (2, 0), so the gcd is 2. Python’s math.gcd and C++’s std::gcd do the same.

New to the technique behind this problem? Watch it run step by step:

Two Pointers Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description