InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Greatest Common Divisor of Strings

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug