VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-derangement-sequence/

⇱ Largest Derangement of a Sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest Derangement of a Sequence

Last Updated : 7 Jul, 2025

Given any sequence S, find the largest derangement. A derangement D is any permutation such that no two elements at the same position in S and D are equal.  The "largest derangement" of a sequence refers to the derangement that results in the lexicographically largest permutation

Examples: 

Input : seq[] = {5, 4, 3, 2, 1}
Output : 4 5 2 1 3

Input : seq[] = {56, 21, 42, 67, 23, 74}
Output : 74, 67, 56, 42, 21, 23

Since we are interested in generating the largest derangement, we start putting larger elements in more significant positions. Start from left, at any position i place the next largest element among the values of the sequence which have not yet been placed in positions before.

To scan all positions takes n iteration. In each iteration we are required to find a maximum number, so a trivial implementation would be O(n^2) complexity, However, if we use a data structure like max-heap to find the maximum element, then the complexity reduces to O(n Log n)


Output
Largest Derangement 
52 92 31 3 13 1 2 

Time Complexity: O(n log n)
Auxiliary Space: O(n), because, we use an N size array to store results.

Note:  The method can be easily modified to obtain the smallest derangement as well.  Instead of a Max Heap, we should use a Min Heap to consecutively get minimum elements

Comment
Article Tags: