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++ program for the above approach #include<bits/stdc++.h> using namespace std;
// Function that finds gcd of 2 strings string gcd(string str1, string str2) { // If str1 length is less than
// that of str2 then recur
// with gcd(str2, str1)
if (str1.length() < str2.length())
{
return gcd(str2, str1);
}
// If str1 is not the
// concatenation of str2
else if (str1.find(str2) != 0)
{
return "" ;
}
else if (str2 == "" )
{
// GCD string is found
return str1;
}
else
{
// Cut off the common prefix
// part of str1 & then recur
return gcd(str1.substr(str2.length()), str2);
}
} // Function to find GCD of array of // strings string findGCD(string arr[], int n)
{ string result = arr[0];
for ( int i = 1; i < n; i++)
{
result = gcd(result, arr[i]);
}
// Return the GCD of strings
return result;
} // Driver Code int main()
{ // Given array of strings
string arr[]={ "GFGGFG" ,
"GFGGFG" ,
"GFGGFGGFGGFG" };
int n = sizeof (arr)/ sizeof (arr[0]);
// Function Call
cout << findGCD(arr, n);
} // This code is contributed by pratham76. |
// Java program for the above approach class GCD {
// Function that finds gcd of 2 strings
static String gcd(String str1, String str2)
{
// If str1 length is less than
// that of str2 then recur
// with gcd(str2, str1)
if (str1.length() < str2.length()) {
return gcd(str2, str1);
}
// If str1 is not the
// concatenation of str2
else if (!str1.startsWith(str2)) {
return "" ;
}
else if (str2.isEmpty()) {
// GCD string is found
return str1;
}
else {
// Cut off the common prefix
// part of str1 & then recur
return gcd(str1.substring(str2.length()),
str2);
}
}
// Function to find GCD of array of
// strings
static String findGCD(String arr[], int n)
{
String result = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
result = gcd(result, arr[i]);
}
// Return the GCD of strings
return result;
}
// Driver Code
public static void
main(String[] args)
{
// Given array of strings
String arr[]
= new String[] { "GFGGFG" ,
"GFGGFG" ,
"GFGGFGGFGGFG" };
int n = arr.length;
// Function Call
System.out.println(findGCD(arr, n));
}
} |
# Python3 program for the above approach # Function that finds gcd of 2 strings def gcd(str1, str2):
# If str1 length is less than
# that of str2 then recur
# with gcd(str2, str1)
if ( len (str1) < len (str2)):
return gcd(str2, str1)
# If str1 is not the
# concatenation of str2
elif ( not str1.startswith(str2)):
return ""
elif ( len (str2) = = 0 ):
# GCD string is found
return str1
else :
# Cut off the common prefix
# part of str1 & then recur
return gcd(str1[ len (str2):], str2)
# Function to find GCD of array of # strings def findGCD(arr, n):
result = arr[ 0 ]
for i in range ( 1 , n):
result = gcd(result, arr[i])
# Return the GCD of strings
return result
# Driver Code # Given array of strings arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ]
n = len (arr)
# Function Call print (findGCD(arr, n))
# This code is contributed by avanitrachhadiya2155 |
// C# program for // the above approach using System;
class GFG{
// Function that finds gcd // of 2 strings static String gcd(String str1,
String str2)
{ // If str1 length is less than
// that of str2 then recur
// with gcd(str2, str1)
if (str1.Length < str2.Length)
{
return gcd(str2, str1);
}
// If str1 is not the
// concatenation of str2
else if (!str1.StartsWith(str2))
{
return "" ;
}
else if (str2.Length == 0)
{
// GCD string is found
return str1;
}
else
{
// Cut off the common prefix
// part of str1 & then recur
return gcd(str1.Substring(str2.Length),
str2);
}
} // Function to find GCD // of array of strings static String findGCD(String []arr,
int n)
{ String result = arr[0];
for ( int i = 1; i < n; i++)
{
result = gcd(result, arr[i]);
}
// Return the GCD of strings
return result;
} // Driver Code public static void Main(String[] args)
{ // Given array of strings
String []arr = new String[] { "GFGGFG" ,
"GFGGFG" ,
"GFGGFGGFGGFG" };
int n = arr.Length;
// Function Call
Console.WriteLine(findGCD(arr, n));
} } // This code is contributed by shikhasingrajput |
<script> // Javascript program for the above approach
// Function that finds gcd
// of 2 strings
function gcd(str1, str2)
{
// If str1 length is less than
// that of str2 then recur
// with gcd(str2, str1)
if (str1.length < str2.length)
{
return gcd(str2, str1);
}
// If str1 is not the
// concatenation of str2
else if (!str1.startsWith(str2))
{
return "" ;
}
else if (str2.length == 0)
{
// GCD string is found
return str1;
}
else
{
// Cut off the common prefix
// part of str1 & then recur
return gcd(str1.substr(str2.length), str2);
}
}
// Function to find GCD
// of array of strings
function findGCD(arr, n)
{
let result = arr[0];
for (let i = 1; i < n; i++)
{
result = gcd(result, arr[i]);
}
// Return the GCD of strings
return result;
}
// Given array of strings
let arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ];
let n = arr.length;
// Function Call
document.write(findGCD(arr, n));
// This code is contributed by decode2207.
</script> |
GFGGFG
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.
#include <iostream> #include <string> #include <vector> using namespace std;
// Define a function to find the GCD of two strings using the Euclidean algorithm. string gcd_strings(string a, string b) { // Find the lengths of the two strings.
int n = a.length(), m = b.length();
// If the second string is longer than the first, swap them.
if (m > n) {
swap(a, b);
swap(n, m);
}
// If the first string is not divisible by the second string, there is no common divisor.
if (a.compare(0, m, b) != 0) {
return "" ;
}
// Repeat the Euclidean algorithm until the second string divides the first.
while (m > 0) {
int tmp = m;
m = n % m;
n = tmp;
if (m > 0) {
a = b;
b = a.substr(n - m, m);
}
}
// Return the second string, which is the GCD of the two strings.
return b;
} // Define a function to find the GCD of an array of strings. string gcd_array_strings(vector<string> arr) { // Start with the first string in the array.
string gcd = arr[0];
// Iterate over the remaining strings in the array.
for ( int i = 1; i < arr.size(); i++)
{
// Find the GCD of the current string and the previous GCD.
gcd = gcd_strings(gcd, arr[i]);
// If the GCD is an empty string, there is no common divisor.
if (gcd == "" ) {
break ;
}
}
// Return the final GCD, which is the GCD of the entire array.
return gcd;
} // Example usage int main() {
vector<string> arr = { "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" };
cout << gcd_array_strings(arr) << endl; // output: GFGGFG
return 0;
} |
import java.util.ArrayList;
import java.util.List;
public class GCDStrings {
// Function to find the GCD of two strings using the Euclidean algorithm
public static String gcdStrings(String a, String b) {
int n = a.length();
int m = b.length();
// If the second string is longer than the first, swap them
if (m > n) {
String temp = a;
a = b;
b = temp;
int tempLen = n;
n = m;
m = tempLen;
}
// If the first string is not divisible by the second string, there is no common divisor
if (!a.startsWith(b)) {
return "" ;
}
// Repeat the Euclidean algorithm until the second string divides the first
while (m > 0 ) {
int temp = m;
m = n % m;
n = temp;
if (m > 0 ) {
a = b;
b = a.substring(n - m, n);
}
}
// Return the second string, which is the GCD of the two strings
return b;
}
// Function to find the GCD of an array of strings
public static String gcdArrayStrings(List<String> arr) {
// Start with the first string in the array
String gcd = arr.get( 0 );
// Iterate over the remaining strings in the array
for ( int i = 1 ; i < arr.size(); i++) {
// Find the GCD of the current string and the previous GCD
gcd = gcdStrings(gcd, arr.get(i));
// If the GCD is an empty string, there is no common divisor
if (gcd.isEmpty()) {
break ;
}
}
// Return the final GCD, which is the GCD of the entire array
return gcd;
}
// Example usage
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)); // Output: GFGGFG
}
} |
# Define a function to find the GCD of two strings using the Euclidean algorithm. def gcd_strings(a, b):
# Find the lengths of the two strings.
n, m = len (a), len (b)
# If the second string is longer than the first, swap them.
if m > n:
a, b = b, a
n, m = m, n
# If the first string is not divisible by the second string, there is no common divisor.
if a ! = b * (n / / m):
return ""
# Repeat the Euclidean algorithm until the second string divides the first.
while m > 0 :
n, m = m, n % m
if m > 0 :
a, b = b, a[m:n]
# Return the second string, which is the GCD of the two strings.
return b
# Define a function to find the GCD of an array of strings. def gcd_array_strings(arr):
# Start with the first string in the array.
gcd = arr[ 0 ]
# Iterate over the remaining strings in the array.
for i in range ( 1 , len (arr)):
# Find the GCD of the current string and the previous GCD.
gcd = gcd_strings(gcd, arr[i])
# If the GCD is an empty string, there is no common divisor.
if gcd = = "":
break
# Return the final GCD, which is the GCD of the entire array.
return gcd
# Example usage arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ]
print (gcd_array_strings(arr)) # output: GFGGFG
|
using System;
using System.Collections.Generic;
namespace GCDStringCalculator
{ class Program
{
// Define a function to find the GCD of two strings using the Euclidean algorithm.
static string GcdStrings( string a, string b)
{
// Find the lengths of the two strings.
int n = a.Length, m = b.Length;
// If the second string is longer than the first, swap them.
if (m > n)
{
string temp = a;
a = b;
b = temp;
int tempLength = n;
n = m;
m = tempLength;
}
// If the first string is not divisible by the second string, there is no common divisor.
if (a.Substring(0, m) != b)
{
return "" ;
}
// Repeat the Euclidean algorithm until the second string divides the first.
while (m > 0)
{
int tmp = m;
m = n % m;
n = tmp;
if (m > 0)
{
a = b;
b = a.Substring(n - m, m);
}
}
// Return the second string, which is the GCD of the two strings.
return b;
}
// Define a function to find the GCD of an array of strings.
static string GcdArrayStrings(List< string > arr)
{
// Start with the first string in the array.
string gcd = arr[0];
// Iterate over the remaining strings in the array.
for ( int i = 1; i < arr.Count; i++)
{
// Find the GCD of the current string and the previous GCD.
gcd = GcdStrings(gcd, arr[i]);
// If the GCD is an empty string, there is no common divisor.
if (gcd == "" )
{
break ;
}
}
// Return the final GCD, which is the GCD of the entire array.
return gcd;
}
// Example usage
static void Main( string [] args)
{
List< string > arr = new List< string > { "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" };
Console.WriteLine(GcdArrayStrings(arr));
}
}
} |
// Define a function to find the GCD of two strings using the Euclidean algorithm. function gcdStrings(a, b) {
// If the second string is longer than the first, swap them.
if (b.length > a.length) {
[a, b] = [b, a];
}
// If the first string is not divisible by the second string, there is no common divisor.
if (!a.startsWith(b)) {
return "" ;
}
// Repeat the Euclidean algorithm until the second string divides the first.
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 the second string, which is the GCD of the two strings.
return a;
} // Define a function to find the GCD of an array of strings. function gcdArrayStrings(arr) {
// Start with the first string in the array.
let gcd = arr[0];
// Iterate over the remaining strings in the array.
for (let i = 1; i < arr.length; i++) {
// Find the GCD of the current string and the previous GCD.
gcd = gcdStrings(gcd, arr[i]);
// If the GCD is an empty string, there is no common divisor.
if (gcd === "" ) {
break ;
}
}
// Return the final GCD, which is the GCD of the entire array.
return gcd;
} // Example usage const arr = [ "GFGGFG" , "GFGGFG" , "GFGGFGGFGGFG" ];
console.log(gcdArrayStrings(arr)); // Output: GFGGFG
|
GFGGFG
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)