Check if given permutation of 1 to N is feasible using given operations
Last Updated :
13 Apr, 2023
Given an array arr[] of size N, the task to check if this array is built under following constraints:
- The array can only contain numbers from 1 to N.
- We have to build the array sequentially. It means at first we place 1 then 2 and so on upto N.
- If the array is empty then we can place a number at any position.
- If it is not empty then we can place the next element at the next position of the previous element. In case if the next position is out of array size or already filled up then we can choose any position which is unoccupied and place the number.
Examples:
Input: arr[] = {2, 3, 4, 5, 1}
Output: YES
Explanation:
Initially, the array is empty. So we can place 1 at any position.
We place at position 5(1-based indexing).
As the next position is out of array size.
so we can place 2 at any position. We place it in 1st position.
Then we place 3 at 2nd position, 4 at 3rd position, and 5 at 4th position.
So we can build such an array.
Input: arr[] = {1, 5, 2, 4, 3}
Output: NO
Explanation:
At first we can place 1 at 1st position. Then we have to place 2 at 2nd place
as the 2nd position is empty but 2 is placed at position 3 in that given array.
So such array is not possible to build.
Approach:
- First, Store the indices of every array elements in a map.
- Store the position of the next element in ‘next’. Initially, as the array is empty, next contains the position of 1.
- Iterate over [1, N] and check if the current element is present at next index. If not, return -1.
- In each iteration, mark the current position as visited and update the next to the possible index for next value. If the next index (i + 1) of the current index is not visited, then update next to ( i + 1). Otherwise, if the next possible index exceeds the array indices range, store the position of the next element from the map, as it can be placed at any index before the current index in the map.
- On complete traversal of the array, return true, as all indices have been places at their respective next indices.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool CheckArray( int a[], int n)
{
int i, f = 0, next;
map< int , int > pos, vis;
for (i = 0; i < n; i++) {
pos[a[i]] = i;
}
next = pos[1];
for (i = 1; i <= n; i++) {
vis[next] = 1;
if (i != a[next]) {
return false ;
}
if (next + 1 == n
|| vis[next + 1]) {
next = pos[i + 1];
}
else
next++;
}
return true ;
}
int main()
{
int arr[] = { 2, 3, 4, 5, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
if (CheckArray(arr, N)) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static boolean CheckArray( int [] a, int n)
{
int i, f = 0 , next;
HashMap<Integer,
Integer> pos = new HashMap<Integer,
Integer>();
HashMap<Integer,
Integer> vis = new HashMap<Integer,
Integer>();
vis.put( 0 , 0 );
for (i = 0 ; i < n; i++)
{
pos.put(a[i], i);
}
next = pos.getOrDefault( 1 , 0 );
for (i = 1 ; i <= n; i++)
{
vis.put(next, 1 );
if (i != a[next])
{
return false ;
}
if (next + 1 == n ||
vis.getOrDefault(next + 1 , 0 ) != 0 )
{
next = pos.getOrDefault(i + 1 , 0 );
}
else
next++;
}
return true ;
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , 4 , 5 , 1 };
int N = arr.length;
if (CheckArray(arr, N) == true )
{
System.out.println( "YES" );
}
else
{
System.out.println( "NO" );
}
}
}
|
Python3
def CheckArray(a, n):
f = 0
pos = {}
vis = {}
for i in range (n):
pos[a[i]] = i
next = pos[ 1 ]
for i in range ( 1 , n + 1 ):
vis[ next ] = 1
if (i ! = a[ next ]):
return False
if ( next + 1 = = n or
( next + 1 in vis and
vis[ next + 1 ])):
if (i + 1 in pos):
next = pos[i + 1 ]
else :
next + = 1
return True
arr = [ 2 , 3 , 4 , 5 , 1 ]
N = len (arr)
if (CheckArray(arr, N)):
print ( 'YES' )
else :
print ( 'NO' )
|
C#
using System;
using System.Collections;
class GFG{
static bool CheckArray( int [] a, int n)
{
int i, next;
Hashtable pos = new Hashtable();
Hashtable vis = new Hashtable();
for (i = 0; i < n; i++)
{
pos.Add(a[i], i);
}
if (pos.Contains(1))
next = ( int )pos[1];
else
next = 0;
for (i = 1; i <= n; i++)
{
vis.Add(next, 1);
if (i != a[next])
{
return false ;
}
if (next + 1 == n ||
(vis.Contains(next + 1) &&
( int )vis[next + 1] != 0))
{
if (pos.Contains(i + 1))
next = ( int )pos[i + 1];
else
next = 0;
}
else
next++;
}
return true ;
}
static public void Main()
{
int [] arr = { 2, 3, 4, 5, 1 };
int N = arr.Length;
if (CheckArray(arr, N) == true )
{
Console.WriteLine( "YES" );
}
else
{
Console.WriteLine( "NO" );
}
}
}
|
Javascript
<script>
function CheckArray(a, n)
{
var i, f = 0, next;
var pos = new Map(), vis = new Map();
for (i = 0; i < n; i++) {
pos.set(a[i], i);
}
next = pos.get(1);
for (i = 1; i <= n; i++) {
vis.set(next, 1);
if (i != a[next]) {
return false ;
}
if (next + 1 == n
|| vis.get(next + 1)) {
next = pos.get(i + 1);
}
else
next++;
}
return true ;
}
var arr = [2, 3, 4, 5, 1];
var N = arr.length;
if (CheckArray(arr, N)) {
document.write( "YES" );
}
else {
document.write( "NO" );
}
</script>
|
Time Complexity: O(N) as for loop is executing to traverse each element of the input array. Here, N is size of the input array.
Space Complexity: O(max(N, MAX)) where N is size of input array and MAX is maximum element of the input array. This is because pos map size can go up to MAX and vis size can go upto N.
Share your thoughts in the comments
Please Login to comment...