Skip to main content
  1. LeetCode/

LeetCode 1071: Greatest Common Divisor of Strings

·2 mins· ·
LeetCode Daily Easy String Math Gcd
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: Easy First Attempt: 2025-08-09

  • Total time: 00:00.00

Intuition
#

Think of a “GCD string” as a base substring that, when repeated, forms both str1 and str2. The answer must be a common prefix of both strings, and its length must divide both lengths. A straightforward strategy is to try candidate lengths from long to short and validate by repetition.

Approach
#

High-level steps:

  • Let m = len(str1) and n = len(str2).
  • Define isValid(k) to check whether the prefix str1[:k] can be repeated to form both strings. This requires m % k == 0 and n % k == 0, and that repeating the prefix the appropriate number of times equals str1 and str2.
  • Iterate k from m down to 1; return the first valid prefix. If none works, return an empty string.
class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        m = len(str1)
        n = len(str2)

        def isValid(k):
            base = str1[: k]

            if m % k or n % k:
                return False

            times1 = m // k
            times2 = n // k

            return times1 * base == str1 and times2 * base == str2
            
        
        for i in range(m, 0, -1):
            if isValid(i):
                return str1[:i]
        return ""

Findings
#

  • A valid divisor length must divide both m and n.
  • If str1 + str2 != str2 + str1, there is no common base string; this is a quick early-exit check.
  • Potential optimization: Only test lengths that divide gcd(m, n), or directly test str1[:gcd(m, n)].
  • Complexity of the current approach: worst-case O((m + n) × d), where d is the number of common divisors of m and n; space O(1).

Encountered Problems
#

Related

LeetCode 1497: Check If Array Pairs Are Divisible by k (Remainder Pairing, Modulo)
·2 mins
LeetCode Daily Medium Array Hash Map Modulo Math Counting Complement
Remainder pairing with a hash map; handle 0 and k/2 remainders carefully.
LeetCode 30: Substring with Concatenation of All Words (Brute Force → Counting → Sliding Window)
·3 mins
LeetCode Daily Hard String Sliding Window Two Pointers Hash Map Frequency-Counter Brute-Force
Three approaches: brute force, counting optimization, and sliding window over word-length offsets.
LeetCode 496: Next Greater Element I (Monotonic Stack)
·2 mins
LeetCode Daily Easy Array Stack Monotonic-Stack Hash Map Next Greater Element
Monotonic decreasing stack over nums2 to build next-greater map; answer queries for nums1.
LeetCode 76: Minimum Window Substring
·3 mins
LeetCode Daily Hard Sliding Window String Hash Map Two Pointers Variable Window
LeetCode Problem Solving - Variable Size Sliding Window with Character Counting
LeetCode 1456: Maximum Number of Vowels in a Substring of Given Length
·2 mins
LeetCode Daily Medium Sliding Window String Vowel Counting Fixed Window
LeetCode Problem Solving - Fixed Size Sliding Window with Vowel Counting
LeetCode 438: Find All Anagrams in a String
·4 mins
LeetCode Daily Medium Sliding Window Hash Table String Anagram Frequency Counting
LeetCode Problem Solving - Sliding Window with Character Frequency