Logo

dev-resources.site

for different kinds of informations.

Greatest Common Divisor of Strings in Javascript

Published at
11/18/2024
Categories
problemsolving
javascript
leetcode
string
Author
shafiqbd
Author
8 person written this
shafiqbd
open
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.

string Article's
30 articles in total
Favicon
Leetcode β€” 2942. Find Words Containing Character
Favicon
Python day-28 Dictionary, Frequency of character using nested loops
Favicon
Python Day-19 csv file,String methods,ASCII,Task
Favicon
Redis Cache - A String story
Favicon
Python Day-22 String Functions logic using loops, Recursion, Tasks
Favicon
Greatest Common Divisor of Strings in Javascript
Favicon
Day 22- String Functions and Recursion
Favicon
Day 21- String Functions
Favicon
Python Day-21 String functions logic using loops
Favicon
Python Day-20 String functions logic using loops,Task
Favicon
Day 20 - String functions
Favicon
Day 19 - CSV file, ASCII, String methods
Favicon
Python Day 6- String Functions,Looping-For,ifelse conditions and Task
Favicon
Python Day 5 - String functions
Favicon
Mastering String Operations in JavaScript πŸš€
Favicon
String Data Structures and Algorithms: Essential Interview Questions
Favicon
Find the First Non-Repeated Character in a String
Favicon
Longest substring without repeating characters
Favicon
Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.)
Favicon
Write a function that removes duplicate characters from a given string. ( Try to write core JS)
Favicon
Knuth Morris Prat algorithm[Pattern Matching]
Favicon
The JS string replace() method
Favicon
Pergunte ao especialista - Strings
Favicon
Strings
Favicon
C# {String Methods}
Favicon
Extending String for Validation in Dart 3
Favicon
String and Trailing comma, get couple and become, Tuple (): A copy & paste mistake to Error and concept
Favicon
Top 10 String Javascript Interview Coding Question
Favicon
Bash string manipulation
Favicon
C++ ηš„ string η‰©δ»Άεˆ°εΊ•δ½”εΉΎε€‹δ½ε…ƒη΅„οΌŸ

Featured ones: