Given an array arr[] consisting of N positive integers, the task is to find the permutation of first N natural numbers such that the given array arr[] is the prefix maximum array of that permutation. If no such permutation exists, then print “-1”.
Examples:
Input: arr[] = {1, 3, 4, 5, 5}
Output: 1 3 4 5 2
Explanation:
The prefix maximum array of the permutation {1, 3, 4, 5, 2} is {1, 3, 4, 5, 5}.
Input: arr[] = {1, 1, 3, 4}
Output: -1
Naive Approach: The simplest approach to solve the given problem is to generate all possible permutations of the first N natural numbers and check if there exists any permutation whose prefix maximum array is the array arr[] or not. If any such permutation is found, then print that permutation. Otherwise, print “-1”.
Time Complexity: O(N * N!)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the observation that the first occurrence of every number in the arr[] will be at the same place as that in the required permutation. Therefore, after filling the first occurrence of all the elements at their correct positions, fill the remaining numbers in ascending order. Follow the steps below to solve the problem:
- Initialize an array ans[] of size N with all elements as 0 and a vector V[] to store all the unvisited elements in the array.
- Initialize a HashMap M to store the index of the first occurrence of elements
- Traverse the array arr[] and if arr[i] is not present in M, then store the index of arr[i] in M and update ans[i] to arr[i].
- Iterate over the range [1, N] using the variable i and check if i is not present in M, store it in the vector V[].
- Traverse the array ans[] and if the value of ans[i] is 0, then update ans[i] to V[j] and increment j by 1.
- After completing the above steps, check if the maximum element prefix array is the same as arr[]. If found to be true, then print the array ans[] as the result. Otherwise, print “-1”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkPermutation(
int ans[], int a[], int n)
{
int Max = INT_MIN;
for ( int i = 0; i < n; i++) {
Max = max(Max, ans[i]);
if (Max != a[i])
return false ;
}
return true ;
}
void findPermutation( int a[], int n)
{
int ans[n] = { 0 };
unordered_map< int , int > um;
for ( int i = 0; i < n; i++) {
if (um.find(a[i]) == um.end()) {
ans[i] = a[i];
um[a[i]] = i;
}
}
vector< int > v;
int j = 0;
for ( int i = 1; i <= n; i++) {
if (um.find(i) == um.end()) {
v.push_back(i);
}
}
for ( int i = 0; i < n; i++) {
if (ans[i] == 0) {
ans[i] = v[j];
j++;
}
}
if (checkPermutation(ans, a, n)) {
for ( int i = 0; i < n; i++) {
cout << ans[i] << " " ;
}
}
else
cout << "-1" ;
}
int main()
{
int arr[] = { 1, 3, 4, 5, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
findPermutation(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static boolean checkPermutation( int ans[], int a[],
int n)
{
int Max = Integer.MIN_VALUE;
for ( int i = 0 ; i < n; i++)
{
Max = Math.max(Max, ans[i]);
if (Max != a[i])
return false ;
}
return true ;
}
static void findPermutation( int a[], int n)
{
int ans[] = new int [n];
HashMap<Integer, Integer> um = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
if (!um.containsKey(a[i]))
{
ans[i] = a[i];
um.put(a[i], i);
}
}
ArrayList<Integer> v = new ArrayList<>();
int j = 0 ;
for ( int i = 1 ; i <= n; i++)
{
if (!um.containsKey(i))
{
v.add(i);
}
}
for ( int i = 0 ; i < n; i++)
{
if (ans[i] == 0 )
{
ans[i] = v.get(j);
j++;
}
}
if (checkPermutation(ans, a, n))
{
for ( int i = 0 ; i < n; i++)
{
System.out.print(ans[i] + " " );
}
}
else
System.out.println( "-1" );
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 4 , 5 , 5 };
int N = arr.length;
findPermutation(arr, N);
}
}
|
Python3
import sys
def checkPermutation(ans, a, n):
Max = - sys.maxsize - 1
for i in range (n):
Max = max ( Max , ans[i])
if ( Max ! = a[i]):
return False
return True
def findPermutation(a, n):
ans = [ 0 ] * n
um = {}
for i in range (n):
if (a[i] not in um):
ans[i] = a[i]
um[a[i]] = i
v = []
j = 0
for i in range ( 1 , n + 1 ):
if (i not in um):
v.append(i)
for i in range (n):
if (ans[i] = = 0 ):
ans[i] = v[j]
j + = 1
if (checkPermutation(ans, a, n)):
for i in range (n):
print (ans[i], end = " " )
else :
print ( "-1" )
if __name__ = = "__main__" :
arr = [ 1 , 3 , 4 , 5 , 5 ]
N = len (arr)
findPermutation(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static bool checkPermutation( int [] ans, int [] a,
int n)
{
int Max = Int32.MinValue;
for ( int i = 0; i < n; i++)
{
Max = Math.Max(Max, ans[i]);
if (Max != a[i])
return false ;
}
return true ;
}
static void findPermutation( int [] a, int n)
{
int [] ans = new int [n];
Dictionary< int ,
int > um = new Dictionary< int ,
int >();
for ( int i = 0; i < n; i++)
{
if (!um.ContainsKey(a[i]))
{
ans[i] = a[i];
um[a[i]] = i;
}
}
List< int > v = new List< int >();
int j = 0;
for ( int i = 1; i <= n; i++)
{
if (!um.ContainsKey(i))
{
v.Add(i);
}
}
for ( int i = 0; i < n; i++)
{
if (ans[i] == 0)
{
ans[i] = v[j];
j++;
}
}
if (checkPermutation(ans, a, n))
{
for ( int i = 0; i < n; i++)
{
Console.Write(ans[i] + " " );
}
}
else
Console.Write( "-1" );
}
public static void Main()
{
int [] arr = { 1, 3, 4, 5, 5 };
int N = arr.Length;
findPermutation(arr, N);
}
}
|
Javascript
<script>
function checkPermutation(ans,a,n)
{
let Max = Number.MIN_VALUE;
for (let i = 0; i < n; i++)
{
Max = Math.max(Max, ans[i]);
if (Max != a[i])
return false ;
}
return true ;
}
function findPermutation(a,n)
{
let ans = new Array(n);
for (let i=0;i<n;i++)
{
ans[i]=0;
}
let um = new Map();
for (let i = 0; i < n; i++)
{
if (!um.has(a[i]))
{
ans[i] = a[i];
um.set(a[i], i);
}
}
let v = [];
let j = 0;
for (let i = 1; i <= n; i++)
{
if (!um.has(i))
{
v.push(i);
}
}
for (let i = 0; i < n; i++)
{
if (ans[i] == 0)
{
ans[i] = v[j];
j++;
}
}
if (checkPermutation(ans, a, n))
{
for (let i = 0; i < n; i++)
{
document.write(ans[i] + " " );
}
}
else
document.write( "-1" );
}
let arr=[1, 3, 4, 5, 5];
let N = arr.length;
findPermutation(arr, N);
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)