VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-original-permutation-from-given-array-of-inversions/

⇱ Generate original permutation from given array of inversions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate original permutation from given array of inversions

Last Updated : 23 Jul, 2025

Given an array arr[] of size N, where arr[i] denotes the number of elements on the left that are greater than the ith element in the original permutation. The task is to find the original permutation of [1, N] for which given inversion array arr[] holds valid.

Examples:

Input: arr[] = {0, 1, 1, 0, 3}
Output: 4 1 3 5 2
Explanation:
The original permutation is ans[] = {4, 1, 3, 5, 2} 
ans[0] = 4. 
ans[1] = 1. Since {4} exists on its left, which exceeds 1, arr[1] = 1 holds valid. 
ans[2] = 3. Since {4} exists on its left, which exceeds 3, arr[2] = 1 holds valid. 
ans[3] = 5. Since no elements on its left exceeds 5, arr[3] = 0 holds valid. 
ans[4] = 2. Since {4, 3, 5} exists on its left, which exceeds 2, arr[4] = 3 holds valid.

Input: arr[] = {0, 1, 2}
Output: 3 2 1

Naive Approach: The simplest approach is to generate all the permutations of N number and for each permutation, check if its elements satisfy the inversions given by the array arr[]. If such permutation is found, print it.

Time Complexity: O(N!)
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach, the idea is to use a Segment Tree. Follow the below steps to solve the problem:

  1. Build a segment tree of size N and initialize all leaf nodes with value 1.
  2. Traverse the given array from right to left. For example, if the current index is N - 1, i.e, none of the elements are visited. So, the arr[i] is the number of elements that should be greater than the element which has to be at this position. So, the answer for this element is the (N - arr[N - 1])th element in the segment tree corresponds to that element. After that, mark that element as 0 to avoid its counting again.
  3. Similarly, find (i + 1 - arr[i])th element in the segment tree, for each i from (N - 1) to 0.
  4. After finding the answer for arr[i], let it be temp, store it in some array ans[], and update the node having index temp with 0.
  5. Finally, print the answer array ans[] in reversed order as the original permutation.

Below is the implementation of the above approach:


Output: 
4 1 3 5 2

 

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

Related Topic: Segment Tree

Comment