Skip to content
BytePatterns

Greatest Common Divisor of Strings

EasyMath & Number Theory#gcd#string-period~15m

Problem

A string t divides a string s when s is t written one or more times in a row. Given two strings a and b, return the longest string that divides both of them, or an empty string when no string does.

Examples

Input:  a = "ABCABC", b = "ABC"
Output: "ABC"
Input:  a = "ABABAB", b = "ABAB"
Output: "AB"
Why:    AB divides both, while ABAB does not divide ABABAB
Input:  a = "LOOP", b = "POOL"
Output: ""
Why:    edge case, the strings share no repeating unit at all

Hints

0 / 3

Stuck on the idea rather than the code? GCD and Euclid covers it.