Skip to content
Related Articles

Related Articles

Sort an array of strings by replacements with their GCD with elements from another array

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 07 Mar, 2022

Given two arrays of strings arr[] and k[] of size N and M respectively, the task is to sort the array arr[] after replacing each array element arr[i] with the GCD of arr[i] and k[j], where 0 ≤ i < N and 0 ≤ j < M. If it is not possible to sort the array, then print -1.

Note: The GCD of two strings A and B is the smallest string, which when concatenated multiple times, becomes equal to A and B. If no such string exists, return an empty string.


Input:  arr[] = { ‘geeks’, ‘for’, ‘geeks’ },  k[] = { ‘geeksgeeks’, ‘for’ }
Output:  { ‘ ‘, ‘for’, ‘geeks’ }
arr[0] = GCD(‘geeks’, ‘for’) = ‘ ‘
arr[1] = GCD(‘for’, ‘for’) = ‘for’
arr[2] = GCD(‘geeks’, ‘geeksgeeks’) = ‘geeks’ 
arr[0] < arr[1] < arr[2]

Input:  arr[] = { ‘aacd’, ‘abdc’, ‘acac’, ‘aaaa’ },  k[] = {‘aa’, ‘ac’}
Output: -1

Approach: The given problem can be solved greedily. Follow the steps below to solve the problem:

Below is the implementation.


# Python implementation of the
# above approach
# Function to find gcd of two numbers
def GCD(a, b):
    if(b == 0):
        return a
        return GCD(b, a % b)
# Function to find GCD of two strings
def StringGCD(a, b):
    # Length of gcd of two strings
    gcd = GCD(len(a), len(b))
    if a[:gcd] == b[:gcd]:
        if a*(len(b)//gcd) == b*(len(a)//gcd):
            return a[:gcd]
    # GCD of strings does not exist
    return ' '
# Function to check if the array is
# sorted in increasing order or not
def isIncreasing(arr):
    for i in range(len(arr)-1):
        if arr[i] >= arr[i + 1]:
            return False
    return True
# Function to check if arr[] can
# be sorted in increasing order
def sortByGcd(arr, k):
      # Previous string
    prev = ''
    # Iterate through the array
    for i in range(len(arr)):
        # Initialize optimal
        # element by arr[i]
        optEle = arr[i]
        # Flag to find first
        # string > prev
        flag = True
        for idx in range(len(k)):
            # Gcd of two strings
            Ele = StringGCD(arr[i], k[idx])
            # If Ele > prev and flag is set
            if Ele > prev and flag:
                  # Update optEle
                optEle = Ele
                # Update Flag
                flag = False
            # If Ele > prev
            if Ele > prev:
                # Update optEle
                optEle = min(optEle, Ele)
        # Update arr[i] by optEle
        arr[i] = optEle
        # Update prev by arr[i]
        prev = arr[i]
    # Check is arr[] is sorted in ascending order
    if isIncreasing(arr):
        return arr
    # Sorted order is not possible
        return -1
# Driver Code
arr = ['geeks', 'for', 'geeks']
k = ['geeks', 'for']
print(sortByGcd(arr, k))

Time Complexity: O(N * K * log(min(N, K))
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!