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:  



  1. Create a recursive function gcd(str1, str2).
  2. If the length of str2 is more than str1 then we will recur with gcd(str2, str1).
  3. Now if str1 doesn’t start with str2 then return an empty string.
  4. 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.
  5. The string returned after the above steps are the gcd of the given array of string.

Below is the implementation of the above approach:
 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shikhasingrajput