Increasing permutation of first N natural numbers
Last Updated :
07 Mar, 2022
Given a permutation {P1, P2, P3, ….. PN) of first N natural numbers. The task is to check if it is possible to make the permutation increasing by swapping any two numbers. If it is already in increasing order, do nothing.
Examples:
Input: a[] = {5, 2, 3, 4, 1}
Output: Yes
Swap 1 and 5
Input: a[] = {1, 2, 3, 4, 5}
Output: Yes
Already in increasing order
Input: a[] = {5, 2, 1, 4, 3}
Output: No
Approach: Let K be the number of positions i at which P1 ? i (1 based indexing). If K = 0, the answer is Yes as the permutation can be left as is. If K = 2, the answer is also Yes: swap the two misplaced elements. (Notice K = 1 is never possible as if any element is put in the wrong position, the element that was meant to be in that position must also be misplaced.). If K > 2 then the answer is No: a single swap can only affect two elements and can thus only correct at most two misplacements.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int a[], int n)
{
int k = 0;
for ( int i = 0; i < n; i++) {
if (a[i] != i + 1)
k++;
}
if (k <= 2)
return true ;
return false ;
}
int main()
{
int a[] = { 5, 2, 3, 4, 1 };
int n = sizeof (a) / sizeof (a[0]);
if (isPossible(a, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean isPossible( int a[], int n)
{
int k = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (a[i] != i + 1 )
k++;
}
if (k <= 2 )
return true ;
return false ;
}
public static void main(String[] args)
{
int a[] = { 5 , 2 , 3 , 4 , 1 };
int n = a.length;
if (isPossible(a, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isPossible(a, n) :
k = 0 ;
for i in range (n) :
if (a[i] ! = i + 1 ) :
k + = 1 ;
if (k < = 2 ) :
return True ;
return False ;
if __name__ = = "__main__" :
a = [ 5 , 2 , 3 , 4 , 1 ];
n = len (a);
if (isPossible(a, n)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static Boolean isPossible( int []a, int n)
{
int k = 0;
for ( int i = 0; i < n; i++)
{
if (a[i] != i + 1)
k++;
}
if (k <= 2)
return true ;
return false ;
}
public static void Main(String[] args)
{
int []a = { 5, 2, 3, 4, 1 };
int n = a.Length;
if (isPossible(a, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isPossible(a, n)
{
let k = 0;
for (let i = 0; i < n; i++) {
if (a[i] != i + 1)
k++;
}
if (k <= 2)
return true ;
return false ;
}
let a = [ 5, 2, 3, 4, 1 ];
let n = a.length;
if (isPossible(a, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...