Greatest Common Divisor of Strings

Strings have a divisor iff str1 + str2 == str2 + str1; if so, the answer is the gcd-length prefix.

Easy
Time O(m + n) Space O(m + n)
LeetCode
2 min read
string gcd math

Problem#

Return the largest string that divides both str1 and str2 (a divides b iff repeating it some integer number of times equals b).

Examples#

  • "ABCABC", "ABC""ABC".
  • "ABABAB", "ABAB""AB"; "LEET", "CODE""".

Constraints#

  • 1 <= str1.length, str2.length <= 1000.

Approach#

A common divisor exists iff str1 + str2 == str2 + str1 (both are repetitions of the same root). If so, the root length is gcd(|str1|, |str2|).

Solution#

Greatest Common Divisor of Strings
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if (str1 + str2 != str2 + str1) return "";
return str1.substr(0, __gcd((int)str1.size(), (int)str2.size()));
}
};

Editorial#

The str1+str2 == str2+str1 test is a clever encoding: two strings commute under concatenation iff they’re powers of a common root. Once we know a common divisor exists, the longest one has length gcd of the two string lengths, mirroring number-theoretic gcd.

Complexity#

  • Time: O(m + n).
  • Space: O(m + n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.