◀ THE GRIND — MATH & GEOMETRY

Greatest Common Divisor of Strings

The drill: Find the longest string that both inputs are built from by repeating it whole-number-of-times — a divisor here means the string tiles perfectly, no partial copy left over. No shared divisor means the answer is empty.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Two strings arrive, and the question is whether some shorter string can be repeated a whole number of times to rebuild each of them exactly, with no partial copy left dangling at the end.

When such a building-block string exists for both inputs, the drill wants the longest one that works for both simultaneously — the greatest common tile, in the same spirit as a greatest common divisor of two numbers.

If the two strings share no such common tile at all, not even a single matching run that divides both evenly, the expected result is an empty string.

EX 01
str1 = "RSRSRS" · str2 = "RSRS"
"RS"
SHORTER REPEATS FEWER TIMES, BASE TILE LENGTH 2
EX 02
str1 = "W" · str2 = "W"
"W"
MINIMUM SIZE, EQUAL SINGLE CHARACTER
EX 03
str1 = "HELLO" · str2 = "WORLD"
""
NO SHARED TILE AT ALL
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

A string only 'divides' another if repeating it some whole number of times reproduces that string exactly — so any candidate divisor's length has to divide both input lengths evenly. That already rules most lengths out.

HINT 2 THE STRUCTURE

If both strings truly share a common building block, swapping their order and gluing them together changes nothing: str1 + str2 must equal str2 + str1. That single check tells you a shared divisor exists at all, without trying any candidate.

HINT 3 ONE STEP FROM THE ANSWER

Once str1 + str2 == str2 + str1 holds, the longest shared tile is exactly the length gcd(len(str1), len(str2)) — take that prefix of either string and it's the answer.

COACH'S BOARD — THE PATTERN, STEP BY STEP
CONCAT-SWAP CHECKPATTERN · STRING GCDstr1 = "RSRSRS" · str2 = "RSRS"
RSRSRS
RSRS
CONCAT CHECK / EUCLID
— empty —
STEP 1

str1='RSRSRS' (len 6), str2='RSRS' (len 4). A shared tile exists exactly when str1+str2 equals str2+str1.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/greatest-common-divisor-of-strings.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if str1 + str2 != str2 + str1:
            return ""
        g = math.gcd(len(str1), len(str2))
        return str1[:g]
TIME O(M+N)SPACE O(M+N)PYTHON · RACE PACE · 6 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED