Greatest Common Divisor of Strings

Updated on 13 June, 2025
Greatest Common Divisor of Strings header image

Problem Statement

In the specified problem, we interact with the concept where one string can "divide" another. Specifically, a string t divides another string s if s can be expressed as t repeated one or more times consecutively. Given two strings, str1 and str2, the task is to determine the largest string x that can divide both str1 and str2. The significance of "largest" here refers to the repeated pattern string x which is the longest possible common divisor in its string form (not merely in length but in the entirety of x).

Examples

Example 1

Input:

str1 = "ABCABC", str2 = "ABC"

Output:

"ABC"

Example 2

Input:

str1 = "ABABAB", str2 = "ABAB"

Output:

"AB"

Example 3

Input:

str1 = "VULTR", str2 = "CODE"

Output:

""

Constraints

  • 1 <= str1.length, str2.length <= 1000
  • str1 and str2 consist of English uppercase letters.

Approach and Intuition

The problem revolves around finding a common substring which, when repeated, constructs both str1 and str2. A naive approach might involve extracting all possible substrings from one string and checking if any can be a divisor of the other, but this could be inefficient.

  • For each string, identify all substrings which are divisors of the string. This means for each substring, check if repeating this substring the appropriate number of times can reconstruct the original string.
  • From these potential divisor substrings, identify those common to both str1 and str2.
  • Among the common divisors, the largest is required.

Examples Explained

The constraints ensure that provided inputs will be of reasonable size for computational purposes and will only consist of uppercase English letters. Thus, our solution needs to operate efficiently within these bounds.

  • Example 1:

    • Input: str1 = "ABCABC", str2 = "ABC"
    • Output: "ABC"
    • Explanation: String "ABC" is a divisor for both "ABCABC" (appearing twice) and "ABC" (appearing once). No longer string qualifies.
  • Example 2:

    • Input: str1 = "ABABAB", str2 = "ABAB"
    • Output: "AB"
    • Explanation: Here, "AB" is the pattern that divides both strings correctly. "ABAB" fits into "ABABAB" but does not divide "ABAB" uniformly.
  • Example 3:

    • Input: str1 = "VULTR", str2 = "CODE"
    • Output: ""
    • Explanation: There is no common substring that can divide both strings, hence output is an empty string.

The strategy involves deriving a solution that not only operates within the computational limits but also ensures the efficiency of identifying potential substrings that can divide both input strings. The solution builds upon the foundation laid by the understanding of substrings and their repetition patterns within larger strings.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    string findGCDString(string stringA, string stringB) {
        // Validate if string concatenation forms equal strings.
        if (stringA + stringB != stringB + stringA) {
            return "";
        }

        // Compute GCD of lengths.
        int lenGCD = gcd(stringA.length(), stringB.length());
        return stringA.substr(0, lenGCD);
    }
};

The provided C++ solution is designed to solve the problem of finding the greatest common divisor (GCD) of two strings. This approach includes two main steps:

  1. Validate that the concatenation of the two strings in swapped order results in the same string. This ensures that the strings can be constructed of repeated patterns of a GCD string. If not, the function returns an empty string as there is no possible GCD string.

  2. Calculate the GCD of the lengths of the two strings using the built-in GCD function. This value determines the maximum length that the GCD string can have.

  3. Extract and return the substring from the beginning of one of the strings to the determined GCD length. This substring is the greatest common divisor string of the two specified strings.

This method checks if it's feasible to derive a common repeated pattern (gcd) from both strings by merging them in different sequences and then examining the lengths for gcd calculation, ensuring efficiency and accuracy in finding the substring that satisfies the conditions to be the GCD string.

java
class Solution {
    public int calculateGCD(int a, int b) {
        if (b == 0) {
            return a;
        } else {
            return calculateGCD(b, a % b);
        }    
    }
    
    public String longestCommonDivisorOfStrings(String s1, String s2) {
        if (!(s1 + s2).equals(s2 + s1)) {
            return "";
        }
        
        int lengthGCD = calculateGCD(s1.length(), s2.length());
        return s1.substring(0, lengthGCD);
    }
}

The provided solution tackles the problem of finding the greatest common divisor (GCD) of string lengths for two given strings and applying that to determine a common substring. The program uses Java as the implementation language. Below is a concise breakdown of each method within the Solution class:

  • calculateGCD(int a, int b):

    • This method computes the GCD of two integers, using the Euclidean algorithm. It continues to find the remainder of the division of a by b and makes recursive calls until one of the integers becomes zero.
  • longestCommonDivisorOfStrings(String s1, String s2):

    • This method first checks if the concatenation of s1 and s2 is equal to the concatenation of s2 and s1. If they are not equal, it means s1 and s2 do not share the exact sequence of characters in any segment and thus, returns an empty string.
    • If the check passes, the method calculates the GCD of the lengths of s1 and s2.
    • It then returns a substring of s1 from the start up to the GCD length. This substring is the longest common divisor of the given strings based on their lengths.

This approach ensures that the problem is addressed by first establishing the similarity pattern between s1 and s2 and then efficiently finding and returning the longest common substring that divides both strings equally based on their lengths.

python
class Solution:
    def greatestCommonDivisor(self, string1: str, string2: str) -> str:
        if string1 + string2 != string2 + string1:
            return ""

        def computeGCD(x, y):
            while y:
                x, y = y, x % y
            return x

        maxLen = computeGCD(len(string1), len(string2))
        return string1[:maxLen]

The provided solution in Python attempts to find the greatest common divisor (GCD) of two strings. Here is a concise summary of how the solution operates:

  • The function greatestCommonDivisor first checks whether the concatenated results of the two strings in different orders are identical (string1 + string2 versus string2 + string1). If they are not the same, it immediately returns an empty string, indicating that there is no common divisor.

  • Should the strings concatenate in the same order irrespective of sequence, the solution proceeds to compute the GCD of their lengths using a helper function named computeGCD. This function utilizes the Euclidean Algorithm, which repeatedly replaces the larger number by its difference with the smaller number until one of the numbers becomes zero. The other number at that point is the GCD.

  • After determining the GCD of the lengths using computeGCD, the function extracts a substring from the first string (string1) starting from index 0 up to the calculated GCD length (maxLen). This substring is returned as the greatest common divisor of the given strings.

This method effectively leverages mathematical principles to reduce the problem of finding a string GCD to computing a numeric GCD of string lengths, followed by a simple substring operation. This approach ensures efficiency both in computation and in clarity of the resulting code behavior.

Comments

No comments yet.