DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 1071. Greatest Common Divisor of Strings

Approach -> String is considered as divisor , when the lengths of both strings str1 and str2 is divisible by substring length and on repetition of substring should be able to get both strings str1 and str2 , following greedy approach and start with the string which is having less length in str1 and str2

Javascript Code

/**
 * @param {string} str1
 * @param {string} str2
 * @return {string}
 */
var gcdOfStrings = function(str1, str2) {

    let len1 = str1.length;
    let len2 = str2.length;
    let min = Math.min(len1, len2);

    const isDivisor = (l) => {
        if (len1 % l !== 0 || len2 % l !== 0) {
            return false;
        }

        let substring = str1.slice(0, l);
        let f1 = len1 / l;
        let f2 = len2 / l;

        return substring.repeat(f1) === str1 && substring.repeat(f2) === str2;
    };

    for (let i = min; i > 0; i--) {
        if (isDivisor(i)) {
            return str1.slice(0, i);
        }
    }

    return "";

};

Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay