![]() |
VOOZH | about |
Given an array A[] of size N where each element A[i] =max(P[0], P[1], . . ., P[i]), where P[] is a permutation consisting of elements from 1 to N, the task is to find the lexicographically smallest and lexicographically largest permutation that satisfies A[].
Examples:
Input: A[] = {3, 4, 5, 5, 5, 7, 7}
Output: Lexicographically smallest permutation is: {3 4 5 1 2 7 6}.
Lexicographically largest permutation is: { 3 4 5 2 1 7 6}Input: A[] = {2, 4, 4, 4, 6, 6}
Output: Lexicographically smallest permutation is: 2 4 1 3 6 5
Lexicographically largest permutation is: 2 4 3 1 6 5
Approach: This problem can be solved using this idea:
Use a set to store the first N natural number and for each element of A, find the lexicographical element satisfying A using property of set that it stores values in sorted order.
To make a permutation array, push all the natural numbers from 1 to N into a set because every element is required only once.
Below is the implementation of the above approach.
Lexicographically smallest permutation is : 2 4 1 3 6 5 Lexicographically largest permutation is : 2 4 3 1 6 5
Time Complexity: N* logN
Auxiliary Space: O(N)