Skip to main content

Greatest Common Divisor of Strings

Easy
Data Structures and Algorithms
Editorial
Topics:
String
Math
Number Theory

A string x divides another string y when y can be formed by concatenating one or more copies of x. A common divisor string of str1 and str2 must divide both parameters.

Return the longest string that divides both str1 and str2. If no non-empty string has this property, return the empty string.

Example 1:

Input: str1 = "XYZXYZXYZ", str2 = "XYZXYZ"
Output: "XYZ"
Explanation: "XYZ" repeated three times forms str1 and repeated twice forms str2; no longer common repeating block exists.

Example 2:

Input: str1 = "ABCA", str2 = "AB"
Output: ""
Explanation: The two strings are not composed of repetitions of the same non-empty block, so no common divisor string exists.

Example 3:

Input: str1 = "KLMKLM", str2 = "KLMKLM"
Output: "KLMKLM"
Explanation: A string divides itself, and the entire input is the longest possible common divisor.

Constraints:

  • 1 <= str1.length <= 10^3
  • 1 <= str2.length <= 10^3
  • ``str1andstr2 contain only uppercase English letters
  • ``str1andstr2 are non-empty strings

Need help or want more practice?

Practise in an interviewGet AI Coach help