Python 1071.py
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if len(str1) > len(str2):
str1, str2 = str2, str1
if len(str1) == 0:
return ""
if len(str1) > 1 and gcd(len(str1), len(str2)) == 1:
return ""
result = ""
current = ""
for c in str1:
current += c
pattern = "^(" + current + ")+$"
if re.search(pattern, str1) and re.search(pattern, str2):
result = current
return result
Difficulty
and has an acceptance rate of about 54% (1+ million submissions).
Typical patterns to solve this problem:
- Math
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method gcdOfStrings that attempts to find the longest string that can be concatenated repeatedly to form both input strings str1 and str2. The algorithm proceeds through a series of preparatory checks, then iteratively builds candidate prefixes and validates them against both inputs using regular-expression matching.
Input Normalization
The first logical block ensures that the shorter string is always examined as the base for candidate prefixes. By swapping the variables when str1 is longer, the subsequent loops operate over the minimal possible length, reducing the number of iterations required for the search.
if len(str1) > len(str2):
str1, str2 = str2, str1
Empty String Edge Case
Immediately after normalization, the method checks whether the now-shorter string is empty. An empty string cannot contribute any non-trivial divisor, so the function returns an empty result without further processing.
if len(str1) == 0:
return ""
Coprime Length Early Exit
When both strings have length greater than one, the code computes the greatest common divisor of their lengths. If the lengths are coprime (the GCD equals one), no non-empty common divisor string can exist, and the function returns an empty string right away. This early exit prevents unnecessary pattern construction for cases that are mathematically impossible.
if len(str1) > 1 and gcd(len(str1), len(str2)) == 1:
return ""
Pattern Construction and Search Loop
The core of the algorithm iterates over each character of the shorter string, progressively building a candidate prefix stored in current. For each new character, a regular-expression pattern is assembled that matches one or more repetitions of the candidate prefix anchored to the start and end of a string. The pattern is then applied to both str1 and str2. If both strings satisfy the pattern, the candidate becomes the new result.
result = ""
current = ""
for c in str1:
current += c
pattern = "^(" + current + ")+$"
if re.search(pattern, str1) and re.search(pattern, str2):
result = current
Result Accumulation
The variable result holds the longest prefix that has successfully matched both strings up to the current point in the loop. Because the loop proceeds in order from the first character to the last, any later successful match will necessarily be longer than a previous one, ensuring that the final value of result is the longest common divisor string found.
Edge Cases Covered
The implementation explicitly addresses several boundary conditions. When either input is an empty string, the early length check returns an empty result, handling the case where no divisor can exist. The coprime-length guard captures scenarios where the strings’ lengths share no common factor, guaranteeing that the function does not waste effort on impossible matches. The regular-expression validation inherently verifies that the candidate prefix repeats without remainder, thereby handling cases where one string is a multiple of the other, as well as cases where the strings share a partial but non-repeating prefix. If no prefix satisfies the pattern for both strings, the loop completes without updating result, and the method returns an empty string, representing the absence of a common divisor.
Performance Optimizations
The code incorporates several optimizations that reduce computational overhead. Swapping the strings to make str1 the shorter operand limits the number of iterations in the prefix-building loop, directly scaling the work with the smaller length. The coprime-length check serves as a mathematical shortcut that eliminates the need for any pattern matching when a common divisor is impossible, saving the cost of regular-expression compilation and execution. Within the loop, the pattern is constructed incrementally using the growing current string, avoiding the need to recompute the entire candidate from scratch on each iteration. By employing re.search only after the pattern is fully formed, the algorithm avoids unnecessary regex engine invocations for prefixes that have not yet been built. The final assignment to result occurs only when both regex checks succeed, ensuring that the method retains the longest valid divisor without extra comparison logic. These choices collectively keep the runtime focused on the most promising candidates and prevent wasteful processing of clearly invalid cases.
ELI5 - Simplified Explanation
Imagine you have two necklaces made of colorful beads. The goal is to find the longest pattern that repeats over and over to make both necklaces look exactly like they do.
First, the code lines up the necklaces to see which one is shorter. If there are no beads at all, it simply stops. Then, it checks if the lengths of the necklaces allow for a common pattern at all. If the math does not work out, it decides that no pattern fits.
Next, it starts testing tiny pieces of the first necklace one by one. It grows a little block of beads, starting from just one bead, and adds on to it. After adding each new bead, it asks a special question to see if this new block acts like a stamp that could perfectly create both necklaces if used repeatedly. If the block works, it remembers that piece as the best one found so far. It keeps doing this until it has checked the whole first necklace, always remembering the biggest pattern that works for both.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | ||||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | Java | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | Java | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java |
Videos
Solved On The Same Day
- problem 455: Assign Cookies
- problem 500: Keyboard Row
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1748: Sum of Unique Elements
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 216: Combination Sum III
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 470: Implement Rand10() Using Rand7()
- problem 503: Next Greater Element II
- problem 556: Next Greater Element III
- problem 622: Design Circular Queue
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality