Site icon vanitaai.com

LeetCode75: Greatest Common Divisor of Strings

Introduction

The Greatest Common Divisor of Strings problem is a fascinating blend of string manipulation and mathematical logic, commonly featured in coding interviews and the LeetCode 75 study plan. In this challenge, you’re given two non-empty strings, str1 and str2, and your task is to find the largest string x such that both str1 and str2 can be constructed by repeating x one or more times.

This “string GCD” mimics the idea of the greatest common divisor from arithmetic, but applies it to repeated string patterns instead of numbers. To solve this problem, you’ll need to combine insights from modular string patterns, efficient string matching, and the classic Euclidean algorithm.

Given two strings str1 and str2, return the greatest common divisor (GCD) string of the two.

A string x is called a divisor of str if str can be formed by concatenating x one or more times.

Find the largest string x such that:

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""

Constraints:

Python Solution

from math import gcd

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if str1 + str2 != str2 + str1:
            return ""
        max_length = gcd(len(str1), len(str2))
        return str1[:max_length]

Step-by-Step Explanation

Step 1: Import GCD Function

from math import gcd

Step 2: Define the Function

class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:

Step 3: Check Compatibility Using Concatenation

        if str1 + str2 != str2 + str1:
            return ""

Step 4: Find the GCD of String Lengths

        max_length = gcd(len(str1), len(str2))

Step 5: Return the GCD String

        return str1[:max_length]

Why the Concatenation Check Works

If two strings str1 and str2 have the same repeating pattern, then:

str1 + str2 == str2 + str1

Otherwise, they can’t have a common base divisor string.

Time and Space Complexity

This solution uses a string theory trick combined with the mathematical GCD to efficiently find the greatest common divisor of strings. If both strings can be built from the same repeating substring, the problem is reduced to finding the GCD of their lengths.

Greatest Common Divisor of Strings

Exit mobile version