Python3 Program for Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.
Examples:
Input : n = 2
arr[] = {"molzv", "lzvmo"}
Output : 2
Explanation: In first string, we remove
first element("m") from first string and
append it end. Then we move second character
of first string and move it to end. So after
2 operations, both strings become same.
Input : n = 3
arr[] = {"kc", "kc", "kc"}
Output : 0
Explanation: already all strings are equal.
The move to end operation is basically left rotation. We use the approach discussed in check if strings are rotations of each other or not to count number of move to front operations required to make two strings same. We one by one consider every string as the target string. We count rotations required to make all other strings same as current target and finally return minimum of all counts.
Below is the implementation of above approach.
Python 3
import sys
def minimunMoves(arr, n):
ans = sys.maxsize
for i in range (n):
curr_count = 0
for j in range (n):
tmp = arr[j] + arr[j]
index = tmp.find(arr[i])
if (index = = len (arr[i])):
return - 1
curr_count + = index
ans = min (curr_count, ans)
return ans
if __name__ = = "__main__" :
arr = [ "xzzwo" , "zwoxz" , "zzwox" , "xzzwo" ]
n = len (arr)
print ( minimunMoves(arr, n))
|
Output:
5
Time Complexity: O(N3) (N2 due to two nested loops used and N is for the function find() used the inner for loop)
Please refer complete article on Minimum move to end operations to make all strings equal for more details!
Last Updated :
08 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...