Minimum number of prefix reversals to sort permutation of first N numbers
Last Updated :
08 Dec, 2021
Given N numbers that 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 increasing order.
Examples:
Input : a[] = {3, 1, 2}
Output : 2
Step1: Reverse the complete array a, a[] = {2, 1, 3}
Step2: Reverse the prefix(0-1) in s, a[] = {1, 2, 3}
Input : a[] = {1, 2, 4, 3}
Output : 3
Step1: Reverse the complete array a, a[] = {3, 4, 2, 1}
Step2: Reverse the prefix(0-1) in s, a[] = {4, 3, 2, 1}
Step3: Reverse the complete array a, a[] = {1, 2, 3, 4}
The approach to solve this problem is to use BFS.
- 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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[0]);
cout << minimumPrefixReversals(a, n);
return 0;
}
|
Java
import java.util.*;
public class Main
{
public static int minimumPrefixReversals( int [] a)
{
int n = a.length;
String start = "" , destination = "" ;
String original = "" ,modified = "" ;
Node temp = null ;
for ( int i = 0 ; i < n; i++)
start += a[i];
Arrays.sort(a);
for ( int i = 0 ; i < n; i++)
destination += a[i];
Queue<Node> q = new LinkedList<>();
q.add( new Node(start, 0 ));
if (start == destination)
return 0 ;
while (q.size() != 0 )
{
temp = q.poll();
original = temp.string;
for ( int j = 2 ; j <= n; j++)
{
modified = original;
modified = reverse (modified , j);
if (modified.equals(destination))
{
return temp.steps + 1 ;
}
q.add( new Node(modified,temp.steps + 1 ));
}
}
return Integer.MIN_VALUE;
}
public static String reverse (String s , int index)
{
char temp []= s.toCharArray();
int i = 0 ;
while (i < index)
{
char c = temp[i];
temp[i] = temp[index- 1 ];
temp[index- 1 ] = c;
i++;index--;
}
return String.valueOf(temp);
}
public static void main(String []args)
{
int a[] = new int []{ 1 , 2 , 4 , 3 };
System.out.println(minimumPrefixReversals(a));
}
static class Node
{
public String string ;
public int steps;
public Node(String string, int steps)
{
this .string = string;
this .steps= steps;
}
}
}
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public String str;
public int steps;
public Node(String str, int steps)
{
this .str = str;
this .steps= steps;
}
}
public static int minimumPrefixReversals( int [] a)
{
int n = a.Length;
String start = "" , destination = "" ;
String original = "" , modified = "" ;
Node temp = null ;
for ( int i = 0; i < n; i++)
start += a[i];
Array.Sort(a);
for ( int i = 0; i < n; i++)
destination += a[i];
Queue<Node> q = new Queue<Node>();
q.Enqueue( new Node(start, 0));
if (start == destination)
return 0;
while (q.Count != 0)
{
temp = q.Dequeue();
original = temp.str;
for ( int j = 2; j <= n; j++)
{
modified = original;
modified = reverse (modified , j);
if (modified.Equals(destination))
{
return temp.steps + 1;
}
q.Enqueue( new Node(modified, temp.steps + 1));
}
}
return int .MinValue;
}
public static String reverse (String s, int index)
{
char []temp = s.ToCharArray();
int i = 0;
while (i < index)
{
char c = temp[i];
temp[i] = temp[index - 1];
temp[index - 1] = c;
i++;index--;
}
return String.Join( "" , temp);
}
public static void Main(String []args)
{
int []a = new int []{1, 2, 4, 3};
Console.WriteLine(minimumPrefixReversals(a));
}
}
|
Javascript
<script>
class Node
{
constructor(string,steps)
{
this .string = string;
this .steps= steps;
}
}
function minimumPrefixReversals(a)
{
let n = a.length;
let start = "" , destination = "" ;
let original = "" ,modified = "" ;
let temp = null ;
for (let i = 0; i < n; i++)
start += a[i];
a.sort( function (a,b){ return a-b;});
for (let i = 0; i < n; i++)
destination += a[i];
let q = [];
q.push( new Node(start, 0));
if (start == destination)
return 0;
while (q.length != 0)
{
temp = q.shift();
original = temp.string;
for (let j = 2; j <= n; j++)
{
modified = original;
modified = reverse (modified , j);
if (modified == (destination))
{
return temp.steps + 1;
}
q.push( new Node(modified,temp.steps + 1));
}
}
return Number.MIN_VALUE;
}
function reverse (s,index)
{
let temp = s.split( "" );
let i = 0;
while (i < index)
{
let c = temp[i];
temp[i] = temp[index-1];
temp[index-1] = c;
i++;index--;
}
return (temp).join( "" );
}
let a = [1, 2, 4, 3];
document.write(minimumPrefixReversals(a));
</script>
|
Python3
from queue import Queue
def minimumPrefixReversals( a, n):
start = ""
destination = ""
for i in range (n):
start + = str (a[i])
a.sort()
for i in range (n):
destination + = str (a[i])
qu = Queue()
qu.put((start, 0 ))
if (start = = destination) :
return 0
while qu.not_empty :
p = qu.get()
t = p[ 0 ]
for j in range ( 2 ,n + 1 ) :
r = t
tmpR = list (r)
tmpR[:j] = tmpR[j - 1 :: - 1 ]
r = ''.join(tmpR)
if (r = = destination) :
return p[ 1 ] + 1
qu.put((r, p[ 1 ] + 1 ))
if __name__ = = '__main__' :
a = [ 1 , 2 , 4 , 3 ]
n = len (a)
print (minimumPrefixReversals(a, n))
|
Time Complexity: O(N! * N2)
Auxiliary Space: O(N!)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...