Greatest Common Divisor of Strings
1 approach, code in every language
Problem description
Say a string t divides a string s when s can be built by writing t some whole number of times back to back (for example, "ab" divides "ababab").
Given two strings str1 and str2, return the longest string x that divides both of them. If there is no such non-empty string, return an empty string.
Example 1
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
"AB" repeated forms both inputs, and no longer common block exists.
Example 2
Input: str1 = "LEET", str2 = "CODE"
Output: ""
The two strings share no repeating block, so the answer is empty.
Constraints
1 ≤ str1.length ≤ 10^31 ≤ str2.length ≤ 10^3str1 and str2 consist of uppercase English letters only
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Longest Shared Ribbon Tile is our own problem on the technique behind Greatest Common Divisor of Strings: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free