Greatest Common Divisor of Strings (LeetCode 1071): Solution and Explanation

Easy
Math
String

A string x divides s when s is x repeated one or more times. Find the longest x that divides both str1 and str2, or return an empty string if there is none.

Intuition

The direct approach tries every prefix of the shorter string as a candidate block, longest first, and checks whether repeating it rebuilds both strings. That works, but it hides two facts that make the problem almost arithmetic.

First, existence. If both strings are made of the same block x, say str1 is x repeated p times and str2 is x repeated q times, then str1 + str2 and str2 + str1 are both x repeated p + q times, so they are equal. The converse also holds: if the two orders give the same string, the strings share a common block. One comparison settles whether any answer exists.

Second, the length. Any common block has a length that divides both len(str1) and len(str2). When a block exists, the longest one has length exactly gcd(len(str1), len(str2)), just like the greatest common divisor of two numbers.

Euclid's algorithm finds that gcd quickly: replace (a, b) with (b, a mod b) until b is zero. The answer is the prefix of str1 with that length.

Approach: Concatenation test plus Euclid

  1. If str1 + str2 != str2 + str1, return an empty string.
  2. Set a = len(str1) and b = len(str2).
  3. While b is not zero, replace (a, b) with (b, a % b).
  4. Return str1[:a], the prefix whose length is the gcd.

Step-by-step example

str1 = "ABCABC", str2 = "ABC"
  1. str1 + str2 = "ABCABCABC" and str2 + str1 = "ABCABCABC". They are equal, so a common block exists.
  2. Start Euclid with a = 6 and b = 3.
  3. 6 = 2 x 3 + 0, so (a, b) becomes (3, 0).
  4. b is 0, so the gcd is 3.
  5. The first 3 characters of str1 are ABC, which repeats twice in str1 and once in str2. Return "ABC".

Code: Python, Java, C++

1class Solution:
2    def gcdOfStrings(self, str1: str, str2: str) -> str:
3        if str1 + str2 != str2 + str1:
4            return ""
5        a, b = len(str1), len(str2)
6        while b:
7            a, b = b, a % b
8        return str1[:a]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + n)

Building and comparing the two concatenations is linear in the total length. Euclid takes O(log min(m, n)) steps, which is negligible.

Space

O(m + n)

The two concatenated strings each hold m + n characters.

Other approaches

Try every candidate length (time O(min(m, n) * (m + n)), space O(m + n))

For each length k from min(m, n) down to 1, skip k unless it divides both lengths, then check whether repeating str1[:k] rebuilds both strings. Return the first k that works. It is easy to reason about but repeats the full check for several candidates.

Check only the gcd length (time O(m + n), space O(m + n))

Compute g = gcd(m, n) first, then verify that repeating str1[:g] builds both strings. This skips the concatenation and gives the same answer, because if any common block exists, the one of length g works.

Common mistakes

  • Returning str1[:g] without the concatenation check. For "ABCDEF" and "ABC" the gcd of lengths is 3, but ABC does not divide ABCDEF.
  • Assuming the shorter string is the answer whenever it divides the longer one. In "ABABAB" and "ABAB" neither divides the other, yet "AB" divides both.
  • Writing Euclid with subtraction in a loop on very unequal lengths. It still works for these limits, but the modulo version is the standard form and runs in logarithmic steps.

Frequently asked questions

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

If the two orders are equal, the strings commute under concatenation, and a classic result about words says two commuting strings are both powers of the same string. That shared string is a common divisor.

Why is the answer length the gcd of the two lengths?

Every common block's length divides both lengths, so it is at most the gcd. When a common block x exists, the prefix of length gcd(m, n) is x repeated a whole number of times, and that prefix also divides both strings, so it is the longest.

Can the answer be longer than the shorter string?

No. The answer must divide the shorter string, so its length is at most the shorter length. It equals the shorter string exactly when the shorter one divides the longer one.

What is the time complexity?

O(m + n) for the concatenation comparison. Euclid adds only O(log min(m, n)) arithmetic steps.