VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographically-largest-permutation-by-sequentially-inserting-array-elements-at-ends/

⇱ Lexicographically largest permutation by sequentially inserting Array elements at ends - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographically largest permutation by sequentially inserting Array elements at ends

Last Updated : 23 Jul, 2025

Given an array arr[] of size n, the task is to find the lexicographically largest permutation by sequentially inserting the array elements to the front or the back of another array which is to be considered initially empty.

Examples:

Input: arr[] = [3, 1, 2, 4]
Output: 4 3 1 2
Explanation:
The permutations that can be created by sequentially inserting the array elements to the front or the back of the container are {3, 1, 2, 4}, {1, 3, 2, 4}, {2, 3, 1, 4}, {2, 1, 3, 4}, {4, 1, 3, 2}, {4, 2, 3, 1}, {4, 2, 1, 3}, and {4, 3, 1, 2}. Out of which {4, 3, 1, 2} is the lexicographically largest permutation.

Input: arr[] = [1, 2, 3, 4, 5]
Output: 5 4 3 2 1

Approach:

The given problem can be solved by using the Greedy Approach using the deque. The idea is to simply insert the first element into an empty deque, then for the remaining elements, always put the larger element to the front and smaller element to the rear.

Step by step approach:

  1. Initialize a double-ended queue with the first element arr[0].
  2. Iterate through remaining elements in the original array
    • If current element ≥ front of deque, push it to front.
    • Otherwise, push it to back of deque.
  3. Convert deque to array and return.

Output
4 3 1 2 

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment