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

Top comments (0)