Open In App

Check if given permutation of 1 to N is feasible using given operations

Given an array arr[] of size N, the task to check if this array is built under following constraints:

  1. The array can only contain numbers from 1 to N.
  2. We have to build the array sequentially. It means at first we place 1 then 2 and so on upto N.
  3. If the array is empty then we can place a number at any position.
  4. 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:  

  1. First, Store the indices of every array elements in a map.
  2. Store the position of the next element in ‘next’. Initially, as the array is empty, next contains the position of 1.
  3. Iterate over [1, N] and check if the current element is present at next index. If not, return -1.
  4. 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.
  5. 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++ program to Check If we
// can build the given array
// under given constraints.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function return true if we
// can build the array
bool CheckArray(int a[], int n)
{
    int i, f = 0, next;
 
    // First one is to keep position
    // of each element
    // Second one is for marking
    // the current position
    map<int, int> pos, vis;
 
    for (i = 0; i < n; i++) {
        pos[a[i]] = i;
    }
 
    // Initially next contains
    // the position of 1.
    next = pos[1];
 
    for (i = 1; i <= n; i++) {
        // Mark the current
        // position.
        vis[next] = 1;
 
        // If the element is not
        // present at that position
        // then it is impossible
        // to build
        if (i != a[next]) {
            return false;
        }
 
        // Updating the next
        if (next + 1 == n
            || vis[next + 1]) {
 
            // If the next position is
            // out of array size or next
            // position is not empty then
            // we use the map to find the
            // position of the next element
            next = pos[i + 1];
        }
        else
            // Else just increment it
            next++;
    }
 
    return true;
}
 
// Driver code
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 program to check If we
// can build the given array
// under given constraints.
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function return true if we
// can build the array
static boolean CheckArray(int[] a, int n)
{
    int i, f = 0, next;
 
    // First one is to keep position
    // of each element
    // Second one is for marking
    // the current position
    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);
    }
 
    // Initially next contains
    // the position of 1.
    next = pos.getOrDefault(1, 0);
 
    for(i = 1; i <= n; i++)
    {
         
        // Mark the current
        // position.
        vis.put(next, 1);
 
        // If the element is not
        // present at that position
        // then it is impossible
        // to build
        if (i != a[next])
        {
            return false;
        }
 
        // Updating the next
        if (next + 1 == n ||
            vis.getOrDefault(next + 1, 0) != 0)
        {
             
            // If the next position is
            // out of array size or next
            // position is not empty then
            // we use the map to find the
            // position of the next element
            next = pos.getOrDefault(i + 1, 0);
        }
        else
         
            // Else just increment it
            next++;
    }
    return true;
}
 
// Driver code
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");
    }
}
}
 
// This code is contributed by akhilsaini




# Python3 program to check if we
# can build the given array
# under given constraints.
 
# Function return true if we
# can build the array
def CheckArray(a, n):
     
    f = 0
 
    # First one is to keep position
    # of each element
    # Second one is for marking
    # the current position
    pos = {}
    vis = {}
     
    for i in range(n):
        pos[a[i]] = i
 
    # Initially next contains
    # the position of 1.
    next = pos[1]
     
    for i in range(1, n + 1):
         
        # Mark the current
        # position.
        vis[next] = 1
 
        # If the element is not
        # present at that position
        # then it is impossible
        # to build
        if (i != a[next]):
            return False
 
        # Updating the next
        if (next + 1 == n or
           (next + 1 in vis and
                        vis[next + 1])):
             
            # If the next position is
            # out of array size or next
            # position is not empty then
            # we use the map to find the
            # position of the next element
            if(i + 1 in pos):
                next = pos[i + 1]
        else:
             
            # Else just increment it
            next += 1
 
    return True
 
# Driver code
arr = [ 2, 3, 4, 5, 1 ]
N = len(arr)
 
if (CheckArray(arr, N)):
    print('YES')
else:
    print('NO')
 
# This code is contributed by yatinagg




// C# program to check If we
// can build the given array
// under given constraints.
using System;
using System.Collections;
 
class GFG{
 
// Function return true if we
// can build the array
static bool CheckArray(int[] a, int n)
{
    int i, next;
 
    // First one is to keep position
    // of each element
    // Second one is for marking
    // the current position
    Hashtable pos = new Hashtable();
      Hashtable vis = new Hashtable();
 
    for(i = 0; i < n; i++)
    {
        pos.Add(a[i], i);
    }
 
    // Initially next contains
    // the position of 1.
      if (pos.Contains(1))
        next = (int)pos[1];
      else
        next = 0; 
 
    for(i = 1; i <= n; i++)
    {
         
        // Mark the current
        // position.
        vis.Add(next, 1);
 
        // If the element is not
        // present at that position
        // then it is impossible
        // to build
        if (i != a[next])
        {
            return false;
        }
 
        // Updating the next
        if (next + 1 == n ||
           (vis.Contains(next + 1) &&
                (int)vis[next + 1] != 0))
        {
             
            // If the next position is
            // out of array size or next
            // position is not empty then
            // we use the map to find the
            // position of the next element
              if (pos.Contains(i + 1))
                next = (int)pos[i + 1];
              else
                next = 0; 
        }
        else
         
            // Else just increment it
            next++;
    }
    return true;
}
 
// Driver code
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");
    }
}
}
 
// This code is contributed by akhilsaini




<script>
 
// JavaScript program to Check If we
// can build the given array
// under given constraints.
 
// Function return true if we
// can build the array
function CheckArray(a, n)
{
    var i, f = 0, next;
 
    // First one is to keep position
    // of each element
    // Second one is for marking
    // the current position
    var pos = new Map(), vis = new Map();
 
    for (i = 0; i < n; i++) {
        pos.set(a[i], i);
    }
 
    // Initially next contains
    // the position of 1.
    next = pos.get(1);
 
    for (i = 1; i <= n; i++) {
        // Mark the current
        // position.
        vis.set(next, 1);
 
        // If the element is not
        // present at that position
        // then it is impossible
        // to build
        if (i != a[next]) {
            return false;
        }
 
        // Updating the next
        if (next + 1 == n
            || vis.get(next + 1)) {
 
            // If the next position is
            // out of array size or next
            // position is not empty then
            // we use the map to find the
            // position of the next element
            next = pos.get(i + 1);
        }
        else
            // Else just increment it
            next++;
    }
 
    return true;
}
 
// Driver code
var arr = [2, 3, 4, 5, 1];
var N = arr.length;
if (CheckArray(arr, N)) {
    document.write( "YES" );
}
else {
    document.write( "NO" );
}
 
</script>

Output: 
YES

 

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.


Article Tags :