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:

  1. Example 1:

    • Input: str1 = "ABCABC", str2 = "ABC"
    • Output: "ABC"
    • Explanation: "ABC" divides "ABCABC" (it can be repeated twice) and also divides "ABC" (repeated once).
  2. 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".
  3. 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".

Constraints:

  • Both str1 and str2 consist 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 x divides both str1 and str2, then it must be a prefix of both strings.

  • Concatenation check: A useful insight is that if x divides both str1 and str2, then the concatenation str1 + str2 must equal str2 + 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 str1 and str2. Once you compute this value, the candidate string is simply the prefix of str1, or of str2, with that length.

Approaches

Approach 1: mathematical (using GCD)

  1. Concatenation check: First, check whether str1 + str2 is equal to str2 + str1. If they are not equal, no string x can form both str1 and str2 by repeated concatenation, so return "".

  2. Compute the GCD of the lengths: If the check above passes, compute the greatest common divisor of the lengths of str1 and str2. Call this value g.

  3. Extract and return the divisor: The answer is the first g characters of str1. Repeated the right number of times, this substring reconstructs both str1 and str2.

  • Enumerate divisors: Generate every prefix of str1 whose length divides the length of str1, then check whether each one also divides str2.
  • 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"

  1. Check the concatenation property:

    • str1 + str2 gives "ABABABABAB".
    • str2 + str1 gives "ABABABABAB". Since both are equal, a common divisor string might exist.
  2. Compute the GCD of the lengths:

    • len(str1) = 6
    • len(str2) = 4
    • The greatest common divisor of 6 and 4 is 2.
  3. Extract the prefix:

    • The candidate divisor string is the first 2 characters of str1, which is "AB".
  4. 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.

Code implementations

Python implementation

Python3
Python3

. . . .

Java implementation

Java
Java

. . . .

Complexity analysis

  • Time complexity:

    • The concatenation check takes O(n + m) where n and m are the lengths of str1 and str2.

    • 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 + str1 produces 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 g characters, where g is the gcd of the two lengths.

Edge cases

  • No common divisor: Take str1 = "LEET" and str2 = "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" and str2 = "ABC", the answer is the shorter string if it divides the longer one.

  • Identical strings: If str1 equals str2, then the entire string is the answer.

  • 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.

TAGS
Coding Interview Questions
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which job is best for the future in 2050?
What are the strategies for behavioral questions about teamwork?
Which language is best for DSA?
What are the two types of problem solutions?
What is the salary of Nvidia intern?
What is the salary of freshers in Coinbase?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$99

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
About Us
Our Team
Careers
Partners
Contact Us
Become Affiliate
Copyright © 2026 Design Gurus, LLC. All rights reserved.