09 Sept 2026Go / Python / TypeScriptEasy

Greatest Common Divisor of Strings

Find the longest string that can be repeated to construct each of two strings.

Compatible strings commute under concatenation. When they do, the answer is the prefix whose length is the gcd of their lengths.

complexity

O(n + m) time and O(n + m) temporary string space.

solution files

  • Go greatest-common-divisor-of-strings/solution.go
  • Python greatest-common-divisor-of-strings/solution.py
  • TypeScript greatest-common-divisor-of-strings/solution.ts

Solution files

Gogreatest-common-divisor-of-strings/solution.go
package main

func gcdOfStrings(str1 string, str2 string) string {
	if str1+str2 != str2+str1 {
		return ""
	}
	a, b := len(str1), len(str2)
	for b != 0 {
		a, b = b, a%b
	}
	return str1[:a]
}
Pythongreatest-common-divisor-of-strings/solution.py
from math import gcd


class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        return str1[:gcd(len(str1), len(str2))] if str1 + str2 == str2 + str1 else class="syntax-string">""
TypeScriptgreatest-common-divisor-of-strings/solution.ts
function gcdOfStrings(str1: string, str2: string): string {
  if (str1 + str2 !== str2 + str1) return class="syntax-string">"";
  const gcd = (a: number, b: number): number => b === class="syntax-number">0 ? a : gcd(b, a % b);
  return str1.slice(class="syntax-number">0, gcd(str1.length, str2.length));
}