Finding gcd of two strings in JavaScript

In the number system, the Greatest Common Divisor (GCD) of two numbers is that greatest number which divides both the numbers. Similarly, if we apply this concept to strings, the gcd of two strings is the greatest substring (greatest in length) that is present in both the strings.

For example −

If the two strings are −

const str1 = 'abcabc';
const str2 = 'abc';

Then the gcd of these strings will be −

const gcd = 'abc';

We are required to write a JavaScript function that takes in two strings str1 and str2 and computes and returns their gcd.


The code for this will be −

 Live Demo

const str1 = 'abcabc';
const str2 = 'abc';
const findGCD = (str1 = '', str2 = '') => {
   if (str1 + str2 !== str2 + str1){
      // not possible
      // no common element
      return "";
   } else if (str1 == str2){
      return str1;
   } else if (str1.length > str2.length){
      return findGCD(str1.slice(str2.length), str2);
   } else {
      return findGCD(str2.slice(str1.length), str1);
console.log(findGCD(str1, str2));


And the output in the console will be −


Updated on: 27-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started