Minimum move to end operations to make all strings equal

13 Jun, 2022
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 a number of move to front operations required to make two strings the same. We one by one consider every string as the target string. We count rotations required to make all other strings the same as the current target and finally return a minimum of all counts.Below is the implementation of the above approach.  
C++
Java
Python 3
C#
Javascript
// CPP program to make all strings same using// move to end operations.#include <bits/stdc++.h>using namespace std; // Returns minimum number of moves to end// operations to make all strings same.int minimunMoves(string arr[], int n){    int ans = INT_MAX;    for (int i = 0; i < n; i++)    {        int curr_count = 0;          // Consider s[i] as target string and        // count rotations required to make        // all other strings same as str[i].        for (int j = 0; j < n; j++) {             string tmp = arr[j] + arr[j];             // find function returns the index where we            // found arr[i] which is actually count of            // move-to-front operations.            int index = tmp.find(arr[i]);             // If any two strings are not rotations of            // each other, we can't make them same.             if (index == string::npos)                return -1;             curr_count += index;        }         ans = min(curr_count, ans);    }     return ans;} // driver code for above function.int main(){    string arr[] = {"xzzwo", "zwoxz", "zzwox", "xzzwo"};     int n = sizeof(arr)/sizeof(arr[0]);    cout << minimunMoves(arr, n);    return 0;}
// Java program to make all// strings same using move// to end operations.import java.util.*;class GFG{ // Returns minimum number of// moves to end operations// to make all strings same.static int minimunMoves(String arr[], int n){    int ans = Integer.MAX_VALUE;    for (int i = 0; i < n; i++)    {        int curr_count = 0;         // Consider s[i] as target        // string and count rotations        // required to make all other        // strings same as str[i].        String tmp = "";        for (int j = 0; j < n; j++)        {            tmp = arr[j] + arr[j];             // find function returns the            // index where we found arr[i]            // which is actually count of            // move-to-front operations.            int index = tmp.indexOf(arr[i]);             // If any two strings are not            // rotations of each other,            // we can't make them same.            if (index != -1)                curr_count += index;            else                curr_count = -1;         }         ans = Math.min(curr_count, ans);    }     return ans;} // Driver codepublic static void main(String args[]){    String arr[] = {"xzzwo", "zwoxz",                    "zzwox", "xzzwo"};    int n = arr.length;    System.out.println(minimunMoves(arr, n));}} // This code is contributed// by Kirti_Mangal
# Python 3 program to make all strings# same using move to end operations.import sys # Returns minimum number of moves to end# operations to make all strings same.def minimunMoves(arr, n):     ans = sys.maxsize    for i in range(n):         curr_count = 0         # Consider s[i] as target string and        # count rotations required to make        # all other strings same as str[i].        for j in range(n):             tmp = arr[j] + arr[j]             # find function returns the index where            # we found arr[i] which is actually            # count of move-to-front operations.            index = tmp.find(arr[i])             # If any two strings are not rotations of            # each other, we can't make them same.            if (index == len(arr[i])):                return -1             curr_count += index         ans = min(curr_count, ans)     return ans # Driver Codeif __name__ == "__main__":         arr = ["xzzwo", "zwoxz", "zzwox", "xzzwo"]    n = len(arr)    print( minimunMoves(arr, n)) # This code is contributed by ita_c
using System; // C# program to make all// strings same using move// to end operations.public class GFG{ // Returns minimum number of// moves to end operations// to make all strings same.public  static int minimunMoves(string[] arr, int n){    int ans = int.MaxValue;    for (int i = 0; i < n; i++)    {        int curr_count = 0;         // Consider s[i] as target        // string and count rotations        // required to make all other        // strings same as str[i].        string tmp = "";        for (int j = 0; j < n; j++)        {            tmp = arr[j] + arr[j];             // find function returns the            // index where we found arr[i]            // which is actually count of            // move-to-front operations.            int index = tmp.IndexOf(arr[i], StringComparison.Ordinal);             // If any two strings are not            // rotations of each other,            // we can't make them same.            if (index == arr[i].Length)            {                return -1;            }             curr_count += index;        }         ans = Math.Min(curr_count, ans);    }     return ans;} // Driver codepublic static void Main(string[] args){    string[] arr = new string[] {"xzzwo", "zwoxz", "zzwox", "xzzwo"};    int n = arr.Length;    Console.WriteLine(minimunMoves(arr, n));}} // This code is contributed by Shrikant13
<script> // Javascript program to make all// strings same using move// to end operations.         // Returns minimum number of    // moves to end operations    // to make all strings same.    function minimunMoves(arr,n)    {        let ans = Number.MAX_VALUE;    for (let i = 0; i < n; i++)    {        let curr_count = 0;           // Consider s[i] as target        // string and count rotations        // required to make all other        // strings same as str[i].        let tmp = "";        for (let j = 0; j < n; j++)        {            tmp = arr[j] + arr[j];               // find function returns the            // index where we found arr[i]            // which is actually count of            // move-to-front operations.            let index = tmp.indexOf(arr[i]);               // If any two strings are not            // rotations of each other,            // we can't make them same.            if (index == arr[i].length)                return -1;                               curr_count += index;        }           ans = Math.min(curr_count, ans);    }       return ans;    }         // Driver code    let arr=["xzzwo", "zwoxz",                    "zzwox", "xzzwo"];    let n = arr.length;    document.write(minimunMoves(arr, n));             // This code is contributed by avanitrachhadiya2155     </script>
Output:  
5
Time Complexity : O(n3), Where n is the size of given string (n2 for the two nested for loops and n is for the function used as find())Auxiliary Space: O(n)
This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Kirti_Mangal
shrikanth13
ukasp
avanitrachhadiya2155
karthikkrapa18
codewithmini
rotation
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Convert string to char array in C++
Reverse words in a given string