![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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)
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.
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)