Greatest Common Divisor of Strings - Complete Solution Guide
Greatest Common Divisor of Strings is LeetCode problem 1071, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
For two strings s and t , we say " t divides s " if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 . Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB" Example 3: Input: str1 = "LEET", str2 = "CODE" Output: "" Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 c
Detailed Explanation
This problem introduces a unique definition of string division, asking us to find the "greatest common divisor" (GCD) of two strings, `str1` and `str2`. A string `t` is said to "divide" `s` if `s` can be formed by concatenating `t` with itself one or more times. Our task is to locate the *largest* string `x` that satisfies this division property for both `str1` and `str2`. This isn't about traditional substring matching; it's about identifying a common, repeating elemental string that builds up both given strings.
Solution Approach
The provided solution is remarkably elegant, hinging on two key insights. The first is a crucial pre-condition check: `if str1 + str2 != str2 + str1: return ""`. This condition is both necessary and sufficient for two strings to share a common repeating unit. If `str1` is `x` repeated `n` times and `str2` is `x` repeated `m` times, then `str1 + str2` will be `x` repeated `n+m` times, and `str2 + str1` will be `x` repeated `m+n` times. Since `n+m` always equals `m+n`, these concatenated strings *must* be identical. If they're not, it immediately tells us no such common `x` exists, streamlining the process significantly by handling all non-divisible cases (e.g., "ABC" and "ABA"). Once this initial check confirms that a common divisor string *can* exist, the problem simplifies. If `x` divides both `str1` and `str2`, then the length of `x` must divide both `len(str1)` and `len(str2)`. To find the *largest* such `x`, we need to find the *largest possible length* for `x`. This is precisely the greatest common divisor of the numerical lengths: `gcd(len(str1), len(str2))`. The solution leverages the standard Euclidean algorithm for this. Finally, knowing this maximum possible length, the actual common divisor string `x` is simply the prefix of `str1` (or `str2`) up to that calculated GCD length. For instance, with `str1 = "ABABAB"` and `str2 = "ABAB"`, `gcd(6, 4)` is 2, and the answer is `str1[:2]` which is "AB". This works because if `x` is the repeating unit, it logically forms the beginning of both `str1` and `str2`.
Step-by-Step Algorithm
- Step 1: Check if `str1 + str2` is equal to `str2 + str1`. If not, return an empty string because no common divisor string exists.
- Step 2: Calculate the greatest common divisor (GCD) of the lengths of `str1` and `str2` using Euclid's algorithm.
- Step 3: Extract the substring of `str1` (or `str2`) from index 0 up to the GCD length calculated in Step 2.
- Step 4: Return the extracted substring as the result.
Key Insights
- **The Concatenation Commutativity Test:** A fundamental insight is that if two strings `str1` and `str2` share a common string divisor `x`, then `str1 + str2` must be identical to `str2 + str1`. This provides an efficient O(L1+L2) check to confirm the *existence* of a common divisor string before any further calculations.
- **Reduction to Numerical GCD:** Once the existence of a common divisor string is established, the problem of finding its *length* transforms into a standard numerical GCD problem. The length of the greatest common divisor string will always be `gcd(len(str1), len(str2))`, allowing us to leverage efficient algorithms like Euclidean algorithm.
- **Prefix as the Divisor String:** With the existence confirmed and the length determined via numerical GCD, the final step is straightforward: the actual greatest common divisor string is simply the prefix of `str1` (or `str2`) of that calculated GCD length. This holds true because the repeating unit forming both strings must inherently be present at their respective beginnings.
Complexity Analysis
Time Complexity: O(log(min(n, m)))
Space Complexity: O(1)
Topics
This problem involves: Math, String.
Companies
Asked at: Datadog, Infosys, Nvidia.