# Minimum number of prefix reversals to sort permutation of first N numbers in C++

## Description

Given an array of N numbers which have a permutation of first N numbers. In a single operation, any prefix can be reversed. The task is to find the minimum number of such operations such that the numbers in the array are in sorted in increasing order.

## Example

If array is {1, 2, 4, 3} then minimum 3 steps are required to sort an array in increasing order −

• Reverse entire array {3, 4, 2, 1}
• Reverse first two elements {4, 3, 2, 1}
• Reverse entire array {1, 2, 3, 4}

## Algorithm

• Encode the given numbers in a string. Sort the array and encode it into a string destination.
• Then do a BFS from the initial permutation. Each time, check all permutations induced by reversing a prefix of current permutation.
• If it is not visited, put it into the queue with the count of reversals done.
• When the permutation of the encoded string is same as the destination string, return the numbers of reversals required to reach here
• That is, all permutations of strings are done and the minimal of those is returned as the answer.

## Example

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int minimumPrefixReversals(int *a, int n) {
string start = "";
string destination = "", t, r;
for (int i = 0; i < n; i++) {
start += to_string(a[i]);
}
sort(a, a + n);
for (int i = 0; i < n; i++) { destination += to_string(a[i]);
}
queue<pair<string, int> > qu;
pair<string, int> p;
qu.push(make_pair(start, 0));
if (start == destination) {
return 0;
}
while (!qu.empty()) {
p = qu.front();
t = p.first;
qu.pop();
for (int j = 2; j <= n; j++) {
r = t;
reverse(r.begin(), r.begin() + j);
if (r == destination) {
return p.second + 1;
}
qu.push(make_pair(r, p.second + 1));
}
}
}
int main() {
int a[] = { 1, 2, 4, 3 };
int n = sizeof(a) / sizeof(a);
cout << "Minimum reversal: " << minimumPrefixReversals(a, n) << endl;
return 0;
}

## Output

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

Minimum reversal: 3