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 onlySee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI