🎯 Problem: Greatest Common Divisor of Strings
📖 The Real Problem
You are given two strings str1 and str2. Your task is to find the largest string that can divide both strings completely.
What does "divide" mean?
- A string t divides string s if s can be formed by concatenating t with itself one or more times
- Example: "ABC" divides "ABCABC" because "ABC" + "ABC" = "ABCABC"
The Challenge:
- Need to find the GCD string that divides BOTH input strings
- The GCD string must be the largest possible
- Must verify that the GCD actually works for both strings
- Handle cases where no common divisor exists
Why this problem exists:
- Tests understanding of string patterns and periodicity
- Combines mathematical GCD concepts with string manipulation
- Requires recognizing repeating patterns in strings
- Real-world applications in data compression and pattern recognition
💡 Why This Matters
Real-world applications:
- Data Compression - Finding repeating patterns for compression algorithms
- Signal Processing - Identifying periodic signals in data
- DNA Sequence Analysis - Finding repeating genetic patterns
- Text Processing - Pattern matching and string normalization
- Cryptography - String-based encryption patterns
Skills you'll develop:
- ✅ String manipulation and pattern recognition
- ✅ Mathematical GCD algorithm application
- ✅ String concatenation verification
- ✅ Algorithm optimization
- ✅ Edge case handling
📋 Contributor Tasks
Step 1: Understand the Problem
- Read the problem statement carefully
- Work through examples manually on paper
- Understand what "string division" means
- Identify when no solution exists
Step 2: Plan Your Approach
Key Insight:
- If str1 + str2 != str2 + str1, then no common divisor exists
- The length of GCD string must be GCD of the lengths of str1 and str2
- Check if the prefix of GCD length works for both strings
Mathematical Approach:
- Check if str1 + str2 == str2 + str1
- If not, return "" (no solution)
- If yes, find GCD of lengths
- Return prefix of that length
Step 3: Implement the Solution
- Check concatenation equality
- Calculate GCD of string lengths
- Extract prefix of GCD length
- Verify it divides both strings
- Return the result
Step 4: Test Your Solution
- Test with strings that have common divisor
- Test with strings that don't have common divisor
- Test with identical strings
- Test with one string being multiple of another
- Test edge cases (empty strings, single characters)
✅ Expected Outcome
Function Signature:
def gcdOfStrings(str1: str, str2: str) -> str:
"""
Find the largest string that divides both str1 and str2.
Args:
str1: First input string
str2: Second input string
Returns:
str: Largest common divisor string, or "" if none exists
Example:
>>> gcdOfStrings("ABCABC", "ABC")
"ABC"
"""
Expected Behavior:
- ✅ Returns largest string that divides both inputs
- ✅ Returns "" when no common divisor exists
- ✅ Handles strings of different lengths
- ✅ Handles identical strings correctly
- ✅ Efficient implementation
Example Test Cases:
# Test 1: Basic example with common divisor
gcdOfStrings("ABCABC", "ABC") # Returns: "ABC"
# ABC divides ABCABC (ABC+ABC) and ABC (ABC)
# Test 2: No common divisor
gcdOfStrings("LEET", "CODE") # Returns: ""
# No string divides both
# Test 3: One is multiple of other
gcdOfStrings("ABABAB", "ABAB") # Returns: "AB"
# AB divides both strings
# Test 4: Identical strings
gcdOfStrings("ABC", "ABC") # Returns: "ABC"
# Test 5: Complex pattern
gcdOfStrings("ABABABAB", "ABAB") # Returns: "ABAB"
📚 Additional Context & References
Understanding String Division
String Division Definition:
String t divides string s if:
- s = t + t + t + ... + t (n times, where n >= 1)
- Equivalently: s = t * n for some positive integer n
Examples:
"ABC" divides "ABCABC" ✓ (ABC * 2)
"ABC" divides "ABCABCABC" ✓ (ABC * 3)
"AB" divides "ABAB" ✓ (AB * 2)
"AB" does NOT divide "ABC" ✗
Solution Approach
Optimal Solution:
import math
def gcdOfStrings(str1: str, str2: str) -> str:
# Key insight: if str1 + str2 != str2 + str1, no solution
if str1 + str2 != str2 + str1:
return ""
# Find GCD of lengths
gcd_length = math.gcd(len(str1), len(str2))
# Return prefix of GCD length
return str1[:gcd_length]
Why This Works:
- Concatenation Check: If str1 and str2 share a common divisor, then str1+str2 must equal str2+str1
- GCD of Lengths: The largest common divisor string must have length = GCD(len(str1), len(str2))
- Prefix Extraction: The GCD string is the prefix of either string with GCD length
Hints (Use Only If Stuck!)
💡 Hint 1
Think about what happens when you concatenate the strings in different orders. What does it mean if str1+str2 == str2+str1?
💡 Hint 2
The length of the GCD string must divide both string lengths. What mathematical operation finds the largest common divisor of two numbers?
💡 Hint 3
If a common divisor exists, it must be a prefix of both strings. Which prefix length should you try?
Complexity Analysis
Time Complexity: O(n + m)
- n = len(str1), m = len(str2)
- Concatenation check: O(n + m)
- GCD calculation: O(log(min(n, m)))
- String slicing: O(gcd_length)
- Overall: O(n + m)
Space Complexity: O(n + m)
- For string concatenation check
- Could be optimized to O(1) with careful implementation
Edge Cases to Consider
- No common divisor: Return ""
- Identical strings: Return the string itself
- One empty string: Handle gracefully
- Single character strings: Works correctly
- Prime length strings: May have no common divisor
Related Problems
Once you solve this, try:
- GCD of Two Numbers - Mathematical foundation
- Repeated String Match - Similar pattern matching
- Detect Pattern in String - String periodicity
- Longest Common Prefix - String comparison
Helpful Resources
📝 Notes
- Input strings contain only uppercase English letters
- String lengths: 1 to 1000
- Return "" (empty string) when no solution exists
- The GCD string must divide BOTH strings completely
- Concatenation check is necessary and sufficient
Ready to contribute?
- Fork the repository
- Create your solution file
- Test with provided examples
- Submit a pull request!
File Location: exercises/1000_programs/medium/1071_gcd_of_strings.py
🚀 Happy coding!
🎯 Problem: Greatest Common Divisor of Strings
📖 The Real Problem
You are given two strings str1 and str2. Your task is to find the largest string that can divide both strings completely.
What does "divide" mean?
The Challenge:
Why this problem exists:
💡 Why This Matters
Real-world applications:
Skills you'll develop:
📋 Contributor Tasks
Step 1: Understand the Problem
Step 2: Plan Your Approach
Key Insight:
Mathematical Approach:
Step 3: Implement the Solution
Step 4: Test Your Solution
✅ Expected Outcome
Function Signature:
Expected Behavior:
Example Test Cases:
📚 Additional Context & References
Understanding String Division
String Division Definition:
String t divides string s if:
Examples:
Solution Approach
Optimal Solution:
Why This Works:
Hints (Use Only If Stuck!)
💡 Hint 1
Think about what happens when you concatenate the strings in different orders. What does it mean if str1+str2 == str2+str1?💡 Hint 2
The length of the GCD string must divide both string lengths. What mathematical operation finds the largest common divisor of two numbers?💡 Hint 3
If a common divisor exists, it must be a prefix of both strings. Which prefix length should you try?Complexity Analysis
Time Complexity: O(n + m)
Space Complexity: O(n + m)
Edge Cases to Consider
Related Problems
Once you solve this, try:
Helpful Resources
📝 Notes
Ready to contribute?
File Location:
exercises/1000_programs/medium/1071_gcd_of_strings.py🚀 Happy coding!