1071. Greatest Common Divisor of Strings - Detailed Explanation
Problem statement
You are given two strings, str1 and str2. A string x is said to divide another string s if s can be formed by concatenating x one or more times. In other words, there exists an integer n ≥ 1 such that:
s = x repeated n times
The goal is to find the largest string x (in terms of length) that divides both str1 and str2. If there is no such string, return an empty string "".
Examples:
-
Example 1:
- Input:
str1 = "ABCABC",str2 = "ABC" - Output:
"ABC" - Explanation:
"ABC"divides"ABCABC"(it can be repeated twice) and also divides"ABC"(repeated once).
- Input:
-
Example 2:
- Input:
str1 = "ABABAB",str2 = "ABAB" - Output:
"AB" - Explanation:
"AB"divides"ABABAB"(repeated 3 times) and"ABAB"(repeated 2 times). Note that even though"ABAB"divides"ABAB", it does not divide"ABABAB".
- Input:
-
Example 3:
- Input:
str1 = "LEET",str2 = "CODE" - Output:
"" - Explanation:
There is no non-empty string that can be repeatedly concatenated to form both
"LEET"and"CODE".
- Input:
Constraints:
- Both
str1andstr2consist of uppercase English letters. - The lengths of the strings are between 1 and 1000.
This question sits in the array and string group, which coding interview courses teach under the two pointers pattern, where two indices move through one or two sequences in a single pass. Here a number theory identity replaces the scan, so the solution is shorter than a pointer walk. The recurring LeetCode patterns post lists this group alongside the other techniques worth recognizing quickly.
Hints
-
Divisibility property: If a string
xdivides bothstr1andstr2, then it must be a prefix of both strings. -
Concatenation check: A useful insight is that if
xdivides bothstr1andstr2, then the concatenationstr1 + str2must equalstr2 + str1. If this property does not hold, there is no common divisor string. -
GCD of lengths: The maximum possible length of the common divisor string is the greatest common divisor (GCD) of the lengths of
str1andstr2. Once you compute this value, the candidate string is simply the prefix ofstr1, or ofstr2, with that length.
Approaches
Approach 1: mathematical (using GCD)
-
Concatenation check: First, check whether
str1 + str2is equal tostr2 + str1. If they are not equal, no stringxcan form bothstr1andstr2by repeated concatenation, so return"". -
Compute the GCD of the lengths: If the check above passes, compute the greatest common divisor of the lengths of
str1andstr2. Call this valueg. -
Extract and return the divisor: The answer is the first
gcharacters ofstr1. Repeated the right number of times, this substring reconstructs bothstr1andstr2.
Approach 2: brute force (not recommended)
- Enumerate divisors:
Generate every prefix of
str1whose length divides the length ofstr1, then check whether each one also dividesstr2. - Drawback: This approach is correct, and it is slower and more awkward to write than the mathematical method.
Step-by-step walkthrough (mathematical approach)
Let us walk through an example:
Example:
str1 = "ABABAB", str2 = "ABAB"
-
Check the concatenation property:
str1 + str2gives"ABABABABAB".str2 + str1gives"ABABABABAB". Since both are equal, a common divisor string might exist.
-
Compute the GCD of the lengths:
len(str1) = 6len(str2) = 4- The greatest common divisor of 6 and 4 is 2.
-
Extract the prefix:
- The candidate divisor string is the first 2 characters of
str1, which is"AB".
- The candidate divisor string is the first 2 characters of
-
Verification:
- Check that
"AB"repeated 3 times equals"ABABAB"and repeated 2 times equals"ABAB". This confirms that"AB"is the greatest common divisor string.
- Check that
Code implementations
Python implementation
Java implementation
Complexity analysis
-
Time complexity:
-
The concatenation check takes O(n + m) where n and m are the lengths of
str1andstr2. -
Computing the gcd of two numbers is O(log(min(n, m))).
-
Extracting the substring takes O(g), where g is the gcd of the lengths.
-
Overall, the concatenation check dominates, so the approach is efficient.
-
-
Space complexity:
- The concatenation check builds two strings of length n + m, so auxiliary space is O(n + m). A comparison that avoids building them would bring this down to O(1).
Common mistakes
-
Ignoring the concatenation check: Skipping the test
str1 + str2 == str2 + str1produces wrong answers when the two strings do not repeat the same unit. -
Incorrect GCD calculation: Implement the gcd carefully, or call the library function your language provides.
-
Off-by-one errors: When you extract the substring, slice exactly
gcharacters, wheregis the gcd of the two lengths.
Edge cases
-
No common divisor: Take
str1 = "LEET"andstr2 = "CODE", which returns""because the concatenation property does not hold. -
One string divides the other: When one string is exactly the repeated form of the other, as with
str1 = "ABCABC"andstr2 = "ABC", the answer is the shorter string if it divides the longer one. -
Identical strings: If
str1equalsstr2, then the entire string is the answer.
Alternative variations and related problems
-
Greatest common divisor in number theory:
This problem is analogous to finding the GCD of two numbers.
-
String pattern matching problems: Problems that involve repeated patterns in strings, or that search for a repeated substring, often use the same insight.
Two neighbors in the same array and string group are Reverse Words in a String, which rebuilds a string in place, and Product of Array Except Self, which replaces division with two directional passes. Each one trades a brute force scan for a structural observation, as this question does. The full set of string and array techniques is taught in Grokking the Coding Interview with practice problems.

GET YOUR FREE
Coding Questions Catalog

$99

$197

$72