Greatest Common Divisor of Strings

A string t divides a string s if s is t 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, or an empty string if there is none.

30:00

Greatest Common Divisor of Strings
easy
Free written solution
Topics
Companies

A string t divides a string s if s is t 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, or an empty string if there is none.

Example 1:
Input: {"str1":"ABCABC","str2":"ABC"}
Output: ABC
Constraints:
  • 1≤str1.length,str2.length≤10001 \leq \text{str1.length}, \text{str2.length} \leq 1000

  • str1 and str2 consist of English uppercase letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"str1":"ABCABC","str2":"ABC"}

If some block x builds both strings, gluing them in either order gives the same run of x blocks. So compare str1 + str2 with str2 + str1.

str1 (6)

str2 (3)

step 1: do both orders match?

str1 + str2

A
B
C
A
B
C
A
B
C

str2 + str1

A
B
C
A
B
C
A
B
C

compared 0 / 9

Variables
VariableValue
len(str1)6
len(str2)3
DepthFunction Call
Stack empty
0/12