#1071
Easy Algorithms Greatest common divisor of strings
Math String
53.4% acceptance
Feb 25, 2026
5991
1655
For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn gcd_of_strings(str1: String, str2: String) -> String {
if str1.clone() + &str2 != str2.clone() + &str1 { return String::new(); }
fn gcd(a: usize, b: usize) -> usize { if b == 0 { a } else { gcd(b, a % b) } }
let g = gcd(str1.len(), str2.len());
str1[..g].to_string()
}
}