Given the sequence find the lexicographically smallest (earliest in dictionary order) derangement of .
A derangement of S is as any permutation of S such that no two elements in S and its permutation occur at same position.
Input: 3 Output : 2 3 1 Explanation: The Sequence is 1 2 3. Possible permutations are (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2) (3, 2, 1). Derangements are (2, 3, 1), (3, 1, 2). Smallest Derangement: (2, 3, 1) Input : 5 Output : 2 1 4 5 3. Explanation: Out of all the permutations of (1, 2, 3, 4, 5), (2, 1, 4, 5, 3) is the first derangement.
We can modify the method shown in this article: Largest Derangement
Using a min heap we can successively get the least element and place them in more significant positions, taking care that the property of derangement is maintained.
Complexity: O(N * log N)
Below is the C++ implementation.
2 1 4 3 6 5 8 7 10 9
Since we are given a very specific sequence i.e we can calculate the answer even more efficiently.
Divide the original sequence into pairs of two elements, and then swap the elements of each pair.
If N is odd then the last pair needs to be swapped again.
Complexity: We perform at most N/2 + 1 swaps, so the complexity is O(N).
Why does this method work
This method is a very specific application of method 1 and is based on observation. Given the nature of sequence, at position i we already know the least element that can be put, which is either i+1 or i-1. Since we are already given the least permutation of S it is clear that the derangement must start from 2 and not 1 ie of the form i+1 (i = 1). The next element will be of the form i – 1 . The element after this will be i + 1 and then next i – 1. This pattern will continue until the end.
This operation is most easily understood as the swapping of adjacent elements of pairs of elements of S.
If we can determine the least element in constant time, then the complexity overhead from heap is eliminated. Hence from O(N * log N) the complexity reduces to O(N).
Below is the implementation of above approach:
2 1 4 3 6 5 8 7 10 9
Note : The auxiliary space can be reduced to O(1) if we perform the swapping operations on S itself.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.