Imagine you have two strings that are built by repeating smaller patterns, like DNA sequences with repeating base patterns. Your mission is to find the largest common repeating pattern that can construct both strings!
Given two strings str1 and str2, we say that string x divides a string if that string can be formed by concatenating x with itself multiple times. For example, "ab" divides "abababab" because "abababab" = "ab" + "ab" + "ab" + "ab".
Goal: Find the longest string x that divides both str1 and str2. If no such string exists, return an empty string.
Example: If str1 = "ABABAB" and str2 = "ABAB", then "AB" divides both strings, making it the greatest common divisor of strings!
Input & Output
Visualization
Time & Space Complexity
String concatenation and comparison takes O(m+n), GCD calculation is O(log(min(m,n))) which is dominated by string operations
Space needed for string concatenation operations
Constraints
- 1 โค str1.length, str2.length โค 1000
- str1 and str2 consist of English uppercase letters only
- The answer is guaranteed to be unique