Math Fundamentals18 sections · 814 units
Open in Course

GCD of Strings - The Idea

Length relationship

If a string t divides both str1 and str2, then the length of t must divide both len(str1) and len(str2). The longest such t has length gcd(len(str1), len(str2)).

Example: len(ABABABAB) = 8, len(ABAB) = 4. gcd(8, 4) = 4. The candidate string is str1[0:4] = ABAB.

ABAB repeated 22 times gives ABABABAB, and ABAB repeated 11 time gives ABAB. The candidate works, so the answer is ABAB.