#1071

Greatest Common Divisor of Strings

Easy
MathStringString ManipulationMathematical GCD
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can use the properties of the greatest common divisor (GCD) to find the largest string that divides both. If the concatenation of the two strings in both orders is equal, the GCD string is the prefix of either string up to the GCD of their lengths.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if str1 + str2 is equal to str2 + str1. If not, return an empty string.
  2. 2Step 2: Calculate the GCD of the lengths of str1 and str2.
  3. 3Step 3: Return the substring of str1 from the start to the GCD length.
solution.py8 lines
1# Full working Python code
2import math
3
4def gcdOfStrings(str1, str2):
5    if str1 + str2 != str2 + str1:
6        return ""
7    gcd_length = math.gcd(len(str1), len(str2))
8    return str1[:gcd_length]

Complexity note: The time complexity is O(n) due to the string concatenation and GCD calculation, which is efficient compared to the brute-force method.

  • 1The GCD of strings relies on the property of concatenation.
  • 2If two strings can be formed by repeating a common substring, their concatenation in either order must be equal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.