# Minimum move to end operations to make all strings equal in C++

C++Server Side ProgrammingProgramming

## Problem statement

Given n strings that are permutations of each other. We need to make all strings same with an operation that moves first character of any string to the end of it.

## Example

If arr[] = {“abcd”, “cdab”} then 2 moves are required.

• Let us take first string “abcd”. Move character ‘a’ to the end of the string. After this operation string becomes “bcda”
• Now move character ‘b’ to the end of the string. After this operation string becomes “cdab”. Which in turn makes both strings equal

## Algorithm

• Take first string. Let us call it as ‘str1’.
• Create a temp string by concating str1 to str1 as follows −

temp = str1 + str1

• Count rotations required to make all other strings same as current target
• Repeat above steps for all string and return the minimum of all counts.

## Example

#include <iostream>
#include <string>
#include <algorithm>
#include <climits>
#define SIZE(arr) (sizeof(arr) / sizeof(arr))
using namespace std;
int minMoves(string str[], int n) {
int minCnt = INT_MAX;
for (int i = 0; i < n; ++i) {
int cnt = 0;
for (int j = 0; j < n; ++j) {
string temp = str[j] + str[j];
int index = temp.find(str[i]);
if (index != string::npos) {
cnt += index;
}
}
minCnt = min(cnt, minCnt);
}
return minCnt;
}
int main() {
string str[] = {"abcd", "cdab", "bacd", "cdba"};
cout << "Minimum moves: " << minMoves(str, SIZE(str)) << endl;
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Minimum moves: 2