LeetCode Solution: GCD of String Problem

🚀 Day 2 of My Coding Practice! Solved another problem today on LeetCode – 1071. Greatest Common Divisor of String Problem Statement: Given two strings str1 and str2, return the largest string that divides both strings. Key Idea: If a string divides both strings, then: (str1 + str2) must be equal to (str2 + str1). Then the answer length will be: GCD(length of str1, length of str2) Algorithm Steps Input: String str1, String str2 Output: Largest common divisor string Algorithm: Check if (str1 + str2) equals (str2 + str1). If not equal → return empty string. Find gcd of lengths of str1 and str2. Return substring of str1 from 0 to gcd length. Example Walkthrough Input: str1 = "ABCABC" str2 = "ABC" Process: "ABCABCABC" == "ABCABCABC" ✔ GCD(6, 3) = 3 Output: "ABC" Pseudocode function gcdOfStrings(str1, str2): if (str1 + str2) ≠ (str2 + str1): return "" len1 = length of str1 len2 = length of str2 gcdLength = gcd(len1, len2) return substring of str1 from 0 to gcdLength 📌 Concepts Practiced: ✔ String concatenation logic ✔ Mathematical GCD ✔ Problem-solving approach Consistency over intensity 💪 #LeetCode #Java #ProblemSolving #Day2 #100DaysOfCode #BTech

  • text

To view or add a comment, sign in

Explore content categories