DEV Community

Md. Shafiqul Islam
Md. Shafiqul Islam

Posted on

1

Greatest Common Divisor of Strings in Javascript

Image description
Today, I solved the second problem of the LeetCode 75 series. I'd like to share how I approached this problem.

Problem Statement:
You are given two strings, str1 and str2. Return the largest string x such that x divides both str1 and str2.

Examples:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

Input: str1 = "LEET", str2 = "CODE"
Output: ""
**
My Approach**

I divided my solution into three parts:

Check if a common divisor string exists:
First, I check if a common divisor exists by concatenating str1 + str2 and str2 + str1.

If the two concatenated strings are not equal, it means there is no common divisor, and the function returns an empty string ("").

Find the GCD length:
Next, I find the GCD of the lengths of str1 and str2.

I use a recursive gcd() function. If b !== 0, the function calls itself recursively with two arguments:
gcd(a, b) = gcd(b, a % b)
Once b = 0, the function returns a, which is the GCD length.

Example Calculation:

Initial Call: gcd(6, 3)
Since b = 3 is not 0, it recursively calls gcd(3, 6 % 3) → gcd(3, 0)

Second Call: gcd(3, 0)
Now b = 0, so the function returns 3.

Extract the GCD substring:
Finally, I extract the substring from str1 using the gcdlength.

function gcdOfStrings(str1, str2) {
  // recursive function to calculate the GCD of two numbers
  function gcd(a, b) {
    console.log(a, b);
    return b === 0 ? a : gcd(b, a % b);
  }

  // Step 1: Check if str1 and str2 match or not
  if (str1 + str2 !== str2 + str1) {
    return ""; // No common pattern exists
  }

  // Step 2: Find the GCD of the lengths of str1 and str2
  const len1 = str1.length;
  const len2 = str2.length;
  const gcdLength = gcd(len1, len2);

  // Step 3: The largest divisor substring
  return str1.substring(0, gcdLength);
}

// Example usage:
console.log(gcdOfStrings("ABCABC", "ABC")); // Output: "ABC"
console.log(gcdOfStrings("ABABAB", "ABAB")); // Output: "AB"
console.log(gcdOfStrings("LEET", "CODE")); // Output: ""

Enter fullscreen mode Exit fullscreen mode

If you have better solutions or ideas, feel free to share with me.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay