#1071

Greatest Common Divisor of Strings

Easy GCD on lengths

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A string t "divides" s if s is t repeated some number of times. Return the longest string that divides both inputs, or "" if none.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest block that, repeated, builds both strings.

Why this works: if both strings are made of the same block, gluing them in either order gives the same text. The block length must divide both lengths, and the longest such length is their GCD.

Example: str1 = "ABCABC", str2 = "ABC"

"ABCABC"+"ABC" == "ABC"+"ABCABC" ✓gcd(6, 3) = 3 → "ABC"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Trying every prefix length and checking divisibility by brute force, which is much slower and easy to get wrong.