Program to find Greatest Common Divisor (GCD) of N strings
Given an array of string arr[], the task is the Greatest Common Divisor of the given array of string.
In strings ‘A’ and ‘B’, we say “B divides A” if and only if A = concatenation of B more than 1 times.Find the largest string which divides both A and B.
Examples:
Input: arr[] = { “GFGGFG”, “GFGGFG”, “GFGGFGGFGGFG” }
Output: “GFGGFG”
Explanation:
“GFGGFG” is the largest string which divides the whole array elements.
Input: arr = { “Geeks”, “GFG”}
Output: “”
Approach: The idea is to use recursion. Below are the steps:
- Create a recursive function gcd(str1, str2).
- If the length of str2 is more than str1 then we will recur with gcd(str2, str1).
- Now if str1 doesn’t start with str2 then return an empty string.
- If the longer string begins with a shorter string, cut off the common prefix part of the longer string and recur or repeat until one is empty.
- The string returned after the above steps are the gcd of the given array of string.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
string gcd(string str1, string str2)
{
if (str1.length() < str2.length())
{
return gcd(str2, str1);
}
else if (str1.find(str2) != 0)
{
return "" ;
}
else if (str2 == "" )
{
return str1;
}
else
{
return gcd(str1.substr(str2.length()), str2);
}
}
string findGCD(string arr[], int n)
{
string result = arr[0];
for ( int i = 1; i < n; i++)
{
result = gcd(result, arr[i]);
}
return result;
}
int main()
{
string arr[]={ "GFGGFG" ,
"GFGGFG" ,
"GFGGFGGFGGFG" };
int n = sizeof (arr)/ sizeof (arr[0]);
cout << findGCD(arr, n);
}
|
Java
class GCD {
static String gcd(String str1, String str2)
{
if (str1.length() < str2.length()) {
return gcd(str2, str1);
}
else if (!str1.startsWith(str2)) {
return "" ;
}
else if (str2.isEmpty()) {
return str1;
}
else {
return gcd(str1.substring(str2.length()),
str2);
}
}
static String findGCD(String arr[], int n)
{
String result = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
result = gcd(result, arr[i]);
}
return result;
}
public static void
main(String[] args)
{
String arr[]
= new String[] { "GFGGFG" ,
"GFGGFG" ,
"GFGGFGGFGGFG" };
int n = arr.length;
System.out.println(findGCD(arr, n));
}
}
|
Python3
def gcd(str1, str2):
if ( len (str1) < len (str2)):
return gcd(str2, str1)
elif ( not str1.startswith(str2)):
return ""
elif ( len (str2) = = 0 ):
return str1
else :
return gcd(str1[ len (str2):], str2)
def findGCD(arr, n):
result = arr[ 0 ]
for i in range ( 1 , n):
result = gcd(result, arr[i])
return result
arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ]
n = len (arr)
print (findGCD(arr, n))
|
C#
using System;
class GFG{
static String gcd(String str1,
String str2)
{
if (str1.Length < str2.Length)
{
return gcd(str2, str1);
}
else if (!str1.StartsWith(str2))
{
return "" ;
}
else if (str2.Length == 0)
{
return str1;
}
else
{
return gcd(str1.Substring(str2.Length),
str2);
}
}
static String findGCD(String []arr,
int n)
{
String result = arr[0];
for ( int i = 1; i < n; i++)
{
result = gcd(result, arr[i]);
}
return result;
}
public static void Main(String[] args)
{
String []arr = new String[] { "GFGGFG" ,
"GFGGFG" ,
"GFGGFGGFGGFG" };
int n = arr.Length;
Console.WriteLine(findGCD(arr, n));
}
}
|
Javascript
<script>
function gcd(str1, str2)
{
if (str1.length < str2.length)
{
return gcd(str2, str1);
}
else if (!str1.startsWith(str2))
{
return "" ;
}
else if (str2.length == 0)
{
return str1;
}
else
{
return gcd(str1.substr(str2.length), str2);
}
}
function findGCD(arr, n)
{
let result = arr[0];
for (let i = 1; i < n; i++)
{
result = gcd(result, arr[i]);
}
return result;
}
let arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ];
let n = arr.length;
document.write(findGCD(arr, n));
</script>
|
Time Complexity: O(N*log(B)), where N is the number of strings, and B is the maximum length of any string in arr[].
Auxiliary Space: O(1)
Approach 2 (using Euclidean algorithm)
In this approach we need to first find the GCD of the individual strings in the array. Then wecan use the Euclidean algorithm to find the GCD of two strings A and B.
Algorithm:
First find the length of strings A and B.
Let them be n and m.
If m > n, swap A and B.
If A is not divisible by B, return "" (empty string) because there is no common divisor.
Otherwise, repeat the following steps until A is divisible by B:
a. Let C be the remainder when A is divided by B.
b. Set A to B and B to C.
Return B, which is the GCD of A and B.
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string gcd_strings(string a, string b)
{
int n = a.length(), m = b.length();
if (m > n) {
swap(a, b);
swap(n, m);
}
if (a.compare(0, m, b) != 0) {
return "" ;
}
while (m > 0) {
int tmp = m;
m = n % m;
n = tmp;
if (m > 0) {
a = b;
b = a.substr(n - m, m);
}
}
return b;
}
string gcd_array_strings(vector<string> arr)
{
string gcd = arr[0];
for ( int i = 1; i < arr.size(); i++)
{
gcd = gcd_strings(gcd, arr[i]);
if (gcd == "" ) {
break ;
}
}
return gcd;
}
int main() {
vector<string> arr = { "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" };
cout << gcd_array_strings(arr) << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class GCDStrings {
public static String gcdStrings(String a, String b) {
int n = a.length();
int m = b.length();
if (m > n) {
String temp = a;
a = b;
b = temp;
int tempLen = n;
n = m;
m = tempLen;
}
if (!a.startsWith(b)) {
return "" ;
}
while (m > 0 ) {
int temp = m;
m = n % m;
n = temp;
if (m > 0 ) {
a = b;
b = a.substring(n - m, n);
}
}
return b;
}
public static String gcdArrayStrings(List<String> arr) {
String gcd = arr.get( 0 );
for ( int i = 1 ; i < arr.size(); i++) {
gcd = gcdStrings(gcd, arr.get(i));
if (gcd.isEmpty()) {
break ;
}
}
return gcd;
}
public static void main(String[] args) {
List<String> arr = new ArrayList<>();
arr.add( "GFGGFG" );
arr.add( "GFGGFG" );
arr.add( "GFGGFGGFGGFG" );
System.out.println(gcdArrayStrings(arr));
}
}
|
Python
def gcd_strings(a, b):
n, m = len (a), len (b)
if m > n:
a, b = b, a
n, m = m, n
if a ! = b * (n / / m):
return ""
while m > 0 :
n, m = m, n % m
if m > 0 :
a, b = b, a[m:n]
return b
def gcd_array_strings(arr):
gcd = arr[ 0 ]
for i in range ( 1 , len (arr)):
gcd = gcd_strings(gcd, arr[i])
if gcd = = "":
break
return gcd
arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ]
print (gcd_array_strings(arr))
|
C#
using System;
using System.Collections.Generic;
namespace GCDStringCalculator
{
class Program
{
static string GcdStrings( string a, string b)
{
int n = a.Length, m = b.Length;
if (m > n)
{
string temp = a;
a = b;
b = temp;
int tempLength = n;
n = m;
m = tempLength;
}
if (a.Substring(0, m) != b)
{
return "" ;
}
while (m > 0)
{
int tmp = m;
m = n % m;
n = tmp;
if (m > 0)
{
a = b;
b = a.Substring(n - m, m);
}
}
return b;
}
static string GcdArrayStrings(List< string > arr)
{
string gcd = arr[0];
for ( int i = 1; i < arr.Count; i++)
{
gcd = GcdStrings(gcd, arr[i]);
if (gcd == "" )
{
break ;
}
}
return gcd;
}
static void Main( string [] args)
{
List< string > arr = new List< string > { "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" };
Console.WriteLine(GcdArrayStrings(arr));
}
}
}
|
Javascript
function gcdStrings(a, b) {
if (b.length > a.length) {
[a, b] = [b, a];
}
if (!a.startsWith(b)) {
return "" ;
}
while (b.length > 0) {
const tmp = b;
b = a % b;
a = tmp;
if (b.length > 0) {
a = b;
b = tmp.substring(tmp.length - b.length);
}
}
return a;
}
function gcdArrayStrings(arr) {
let gcd = arr[0];
for (let i = 1; i < arr.length; i++) {
gcd = gcdStrings(gcd, arr[i]);
if (gcd === "" ) {
break ;
}
}
return gcd;
}
const arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ];
console.log(gcdArrayStrings(arr));
|
Time complexity ;O(mn), where m is the length of the longest string in the vector and n is the length of the shortest string in the vector.
Space complexity O(1)
Last Updated :
12 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...