VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographical-smallest-and-largest-permutation-from-array-whose-elements-are-max-of-prefix/

⇱ Lexicographical smallest and largest Permutation from Array whose elements are max of Prefix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographical smallest and largest Permutation from Array whose elements are max of Prefix

Last Updated : 23 Jul, 2025

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.

  • For minimum permutation, initialize the curr_max variable to 0 and traverse the array:
    • If the curr_max is less than A[i] choose the A[i]  and put it into the permutation and remove A[i] from set updating curr_max = A[i].
    • Otherwise, from the set, put the first number from the set into the position to make permutation lexicographically minimum and remove the first element of the set.
  • Second, For maximal permutation, again initialize the curr_max variable to 0 and traverse the array:
    • If the curr_max is less than A[i] choose the A[i]  and put it into the permutation and remove A[i] from set updating curr_max = A[i].
    • Otherwise, check the lower bound of A[i] and decrement the iterator to get the largest number smaller than A[i] in the set, and remove it from the set.
  • Let's say the minimum permutation obtained is called mini and the maximum permutation obtained maxi and return that

Below is the implementation of the above approach.


Output
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)

Comment
Article Tags: