Skip to content
Problem 1071 · LeetCode 1071(opens in a new tab)

Greatest Common Divisor of Strings

EasyMath

Say a string t divides a string s when s is just t written one or more times in a row. For example, "PQ" divides "PQPQPQ".

You get two strings, str1 and str2. Find the longest string that divides each of them. If no string divides both, return the empty string.

Example 1

Input:  str1 = "XYZXYZXYZ", str2 = "XYZXYZ"
Output: "XYZ"
Why:    XYZ three times, and XYZ twice
2 more examples and the constraints

Example 2

Input:  str1 = "QQQQ", str2 = "QQQQQQ"
Output: "QQ"
Why:    QQ fits 2 and 3 times; QQQ or longer does not fit both

Example 3

Input:  str1 = "ABAB", str2 = "BABA"
Output: ""
Why:    the strings start with different letters

Constraints

  • 1 ≤ length of str1, length of str2 ≤ 1,000
  • Both strings contain only upper-case English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every prefix lengthO(min(m, n)·(m + n))
  2. Concatenation check + gcdO(m + n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for two strings of 1,000 lettersVerdict
Try every prefix lengthO(min(m, n)·(m + n))
Passes; rebuilds the strings
Concatenation check + gcdO(m + n)
Best; one comparison

m and n are the lengths of str1 and str2.

Edge cases to test

  • Different first letters. "ABAB" and "BABA" share no block: return "".
  • One string divides the other. "XY" and "XYXYXY" give "XY", the shorter string itself.
  • Lengths share only 1. With lengths 5 and 3, the block can only be one letter long, so both must be one repeated letter.
  • Same prefix, bad tail. "MMMMN" and "MM" start alike but the N breaks it: return "".

Common mistakes

  • Returning the shorter string whenever it is a prefix of the longer one, without checking that it repeats all the way.
  • Using the gcd of the lengths without first doing the concatenation check.
  • Trying lengths from short to long and returning the first match, which finds the smallest block, not the largest.

How to talk through it

  1. 1Clarify. Must the block repeat a whole number of times in both? What should come back when there is none?
  2. 2Give the brute force. Try prefix lengths that divide both sizes, longest first, and rebuild.
  3. 3Find the shortcut. Repeats of one block commute, so compare str1 + str2 with str2 + str1.
  4. 4Get the length from math. The longest block has length gcd(m, n); show Euclid on the two lengths.
  5. 5Test out loud. Run "ABAB" with "BABA", one string inside the other, and lengths whose gcd is 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?