File: greatest-common-divisor-of-strings/solution.py

Date: 2026-06-06

Time: 16:57

greatest-common-divisor-of-strings/solution.py

Purpose

This file solves LeetCode 1071 — Greatest Common Divisor of Strings. It finds the largest string x such that both str1 and str2 can be constructed by concatenating copies of x. It's a standalone solution module following the repo's convention of one problem per directory.

Key Components

gcdOfStrings(str1, str2) -> str — The sole public function. Takes two strings and returns their "GCD string," or "" if none exists.

The function is two lines of logic:

1. Compatibility check (line 15): str1 + str2 != str2 + str1 — if concatenation isn't commutative, no common divisor string exists. This is both necessary and sufficient: two strings share a divisor string *if and only if* their concatenations in both orders are identical.

2. Extract the GCD string (line 17): str1[:gcd(len(str1), len(str2))] — the GCD string's length equals the GCD of the two input lengths. Once we know a divisor exists, we just take the prefix of that length.

Patterns

Math-to-string reduction. The key insight is that "string divides string" is structurally identical to "integer divides integer." The concatenation-commutativity check proves the strings share a repeating unit, then the numeric GCD gives its length. This avoids brute-force substring checking entirely.

LeetCode method signature convention. The function is a bare function (not inside a Solution class), matching this repo's style across all problems.

Dependencies

Imports: math.gcd — Python's built-in Euclidean GCD, O(log(min(a,b))) time.

Imported by: greatest-common-divisor-of-strings/test_solution.py directly. The massive "Imported By" list in the prompt is an artifact of the test harness importing across the repo — those test files don't actually use gcdOfStrings.

Flow

1. Concatenate str1 + str2 and str2 + str1. Compare.

2. If unequal → return "" immediately (no common divisor exists).

3. If equal → compute gcd(len(str1), len(str2)), slice str1 to that length, return it.

Total work: O(n + m) for the string concatenation/comparison, O(log(min(n, m))) for the integer GCD. Space: O(n + m) for the concatenated strings.

Invariants

Error Handling

None. The function returns "" for the "no answer" case. No exceptions are raised or caught. Inputs are assumed to be valid non-empty strings per the LeetCode contract.

Topics to Explore

Beliefs