InterviewPrepKit

Home / Coding / Math & Geometry

Greatest Common Divisor of Strings

easy Original β†—
Solving tips
  • Existence test: a common base string exists iff str1 + str2 == str2 + str1 (they commute under concatenation).
  • If it exists, the longest base has length gcd(len(str1), len(str2)), so the answer is str1[:gcd(len1, len2)].
  • Take gcd of the two lengths (numbers), not the string contents; and always run the commutativity check before trusting the prefix.
  • Return '' when no common base exists; this is O(m+n) time and space.

Problem

For two strings s and t, we say t divides s if s can be written as one or more back-to-back copies of t (that is, s = t + t + ... + t). Given strings str1 and str2, return the longest string x such that x divides both str1 and str2. If no such non-empty string exists, return "".

Examples

  • str1 = "ABCABC", str2 = "ABC" β†’ "ABC" β€” "ABC" tiles str1 twice and str2 once.
  • str1 = "ABABAB", str2 = "ABAB" β†’ "AB" β€” "AB" tiles both; the longer common prefix "ABAB" does not divide "ABABAB" because 6 is not a multiple of 4.
  • str1 = "LEET", str2 = "CODE" β†’ "" β€” the strings share no common tiling unit.

Constraints

  • 1 <= len(str1), len(str2) <= 1000
  • Both strings consist of uppercase English letters only.

Think about it first

Hint 1 Any string that divides `str1` is a prefix of `str1`, and its length must divide `len(str1)` exactly. The same holds for `str2`. So a common divisor's length divides both lengths.
Hint 2 The largest length that divides both `len(str1)` and `len(str2)` is `gcd(len(str1), len(str2))`. If any common divisor string exists at all, it is the prefix of that exact length.
Hint 3 There is a one-line test for whether a common divisor exists: `str1 + str2 == str2 + str1`. Two strings commute under concatenation only when both are repetitions of one common base string.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.