VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-find-greatest-common-divisor-gcd-of-n-strings/

⇱ Program to find Greatest Common Divisor (GCD) of N strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find Greatest Common Divisor (GCD) of N strings

Last Updated : 15 Jul, 2025

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:


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)

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.

Output
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) 

Comment