Open In App

Largest Derangement of a Sequence

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given any sequence, find the largest derangement of .
A derangement D                    is any permutation of, such that no two elements at the same position in S                    and D                    are equal. 
The Largest Derangement is such that.

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

Below is the implementation. 

C++

// C++ program to find the largest derangement
#include <bits/stdc++.h>
using namespace std;
 
void printLargest(int seq[], int N)
{
    int res[N]; // Stores result
 
    // Insert all elements into a priority queue
    std::priority_queue<int> pq;
    for (int i = 0; i < N; i++)
        pq.push(seq[i]);   
 
    // Fill Up res[] from left to right
    for (int i = 0; i < N; i++) {
        int d = pq.top();
        pq.pop();
        if (d != seq[i] || i == N - 1) {
            res[i] = d;
        } else {
 
            // New Element popped equals the element
            // in original sequence. Get the next
            // largest element
            res[i] = pq.top();
            pq.pop();
            pq.push(d);
        }
    }
 
    // If given sequence is in descending order then
    // we need to swap last two elements again
    if (res[N - 1] == seq[N - 1]) {
        res[N - 1] = res[N - 2];
        res[N - 2] = seq[N - 1];
    }
 
    printf("\nLargest Derangement \n");
    for (int i = 0; i < N; i++)
        printf("%d ", res[i]);
}
 
// Driver code
int main()
{
    int seq[] = { 92, 3, 52, 13, 2, 31, 1 };
    int n = sizeof(seq)/sizeof(seq[0]);
    printLargest(seq, n);
    return 0;
}

                    

Java

// Java program to find the largest derangement
import java.io.*;
import java.util.Collections;
import java.util.PriorityQueue;
 
class GFG{
     
public static void printLargest(int a[],int n)
{
     PriorityQueue<Integer> pq = new PriorityQueue<>(
         Collections.reverseOrder());
       
      // Insert all elements into a priority queue
      for(int i = 0; i < n; i++)
    {
        pq.add(a[i]);
    }
     
    // Stores result
      int res[] = new int[n];
       
      // Fill Up res[] from left to right
    for(int i = 0; i < n; i++)
    {
        int p = pq.peek();
        pq.remove();
         
        if (p != a[i] || i == n - 1)
        {
            res[i] = p;
        }
        else
        {
             
            // New Element popped equals the element
            // in original sequence. Get the next
            // largest element
            res[i] = pq.peek();
            pq.remove();
            pq.add(p);
        }
    }
     
      // If given sequence is in descending
      // order then we need to swap last two
      // elements again
      if (res[n - 1] == a[n - 1])
    {
        res[n - 1] = res[n - 2];
        res[n - 2] = a[n - 1];
    }
   
      System.out.println("Largest Derangement");
    for(int i = 0; i < n; i++)
    {
        System.out.print(res[i] + " ");
    }
}
 
// Driver code
public static void main(String[] args)
{
      int n = 7;
    int seq[] = { 92, 3, 52, 13, 2, 31, 1 };
     
      printLargest(seq, n);
}
}
 
// This code is contributed by aditya7409

                    

Python3

# Python3 program to find the largest derangement
def printLargest(seq, N) :
 
    res = [0]*N # Stores result
   
    # Insert all elements into a priority queue
    pq = []
    for i in range(N) :
        pq.append(seq[i])  
   
    # Fill Up res[] from left to right
    for i in range(N) :   
        pq.sort()
        pq.reverse()
        d = pq[0]
        del pq[0]
        if (d != seq[i] or i == N - 1) :
            res[i] = d       
        else :       
   
            # New Element popped equals the element
            # in original sequence. Get the next
            # largest element
            res[i] = pq[0]
            del pq[0]
            pq.append(d)
   
    # If given sequence is in descending order then
    # we need to swap last two elements again
    if (res[N - 1] == seq[N - 1]) :   
        res[N - 1] = res[N - 2]
        res[N - 2] = seq[N - 1]
          
    print("Largest Derangement")
    for i in range(N) :
        print(res[i], end = " ")
 
# Driver code
seq = [ 92, 3, 52, 13, 2, 31, 1 ]
n = len(seq)
printLargest(seq, n)
 
# This code is contributed by divyesh072019.

                    

C#

// C# program to find the largest derangement
using System;
using System.Collections.Generic;
class GFG
{
     
    static void printLargest(int[] seq, int N)
    {
        int[] res = new int[N]; // Stores result
      
        // Insert all elements into a priority queue
        List<int> pq = new List<int>();
        for (int i = 0; i < N; i++)
            pq.Add(seq[i]);   
      
        // Fill Up res[] from left to right
        for (int i = 0; i < N; i++)
        {
            pq.Sort();
            pq.Reverse();
            int d = pq[0];
            pq.RemoveAt(0);
            if (d != seq[i] || i == N - 1)
            {
                res[i] = d;
            }
          else
            {
      
                // New Element popped equals the element
                // in original sequence. Get the next
                // largest element
                res[i] = pq[0];
                pq.RemoveAt(0);
                pq.Add(d);
            }
        }
      
        // If given sequence is in descending order then
        // we need to swap last two elements again
        if (res[N - 1] == seq[N - 1])
        {
            res[N - 1] = res[N - 2];
            res[N - 2] = seq[N - 1];
        }    
        Console.WriteLine("Largest Derangement");
        for (int i = 0; i < N; i++)
            Console.Write(res[i] + " ");
    }
 
  // Driver code
  static void Main()
  {
    int[] seq = { 92, 3, 52, 13, 2, 31, 1 };
    int n = seq.Length;
    printLargest(seq, n);
  }
}
 
// This code is contributed by divyeshrabadiya07

                    

Javascript

<script>
 
// JavaScript program to find the largest derangement
 
 
function printLargest(seq, N) {
    let res = new Array(N); // Stores result
 
    // Insert all elements into a priority queue
    let pq = new Array();
    for (let i = 0; i < N; i++)
        pq.push(seq[i]);
 
    // Fill Up res[] from left to right
    for (let i = 0; i < N; i++) {
        pq.sort((a, b) => a - b);
        pq.reverse();
        let d = pq[0];
        pq.shift();
        if (d != seq[i] || i == N - 1) {
            res[i] = d;
        }
        else {
 
            // New Element popped equals the element
            // in original sequence. Get the next
            // largest element
            res[i] = pq[0];
            pq.shift();
            pq.push(d);
        }
    }
 
    // If given sequence is in descending order then
    // we need to swap last two elements again
    if (res[N - 1] == seq[N - 1]) {
        res[N - 1] = res[N - 2];
        res[N - 2] = seq[N - 1];
    }
    document.write("Largest Derangement<br>");
    for (let i = 0; i < N; i++)
        document.write(res[i] + " ");
}
 
// Driver code
let seq = [92, 3, 52, 13, 2, 31, 1];
let n = seq.length;
printLargest(seq, n);
 
// This code is contributed by gfgking
 
</script>

                    

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

 



Previous Article
Next Article

Similar Reads

Smallest Derangement of Sequence
Given the sequence [Tex]\ S = {1, 2, 3 \dots N} [/Tex]find the lexicographically smallest (earliest in dictionary order) derangement of [Tex]\ S [/Tex]A derangement of S is any permutation of S such that no two elements in S and its permutation occur at the same position. Examples: Input: 3 Output : 2 3 1 Explanation: The Sequence is 1 2 3. Possibl
11 min read
Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
Given a sequence of integers of even length 'n', the task is to find the minimum number of operations required to convert the sequence to follow the rule a[i]=a[i+2] where 'i' is the index. The operation here is to replace any element of the sequence with any element. Examples: Input : n=4 ; Array : 3, 1, 3, 2 Output : 1 If we change the last eleme
11 min read
Convert an unbalanced bracket sequence to a balanced sequence
Given an unbalanced bracket sequence of '(' and ')', convert it into a balanced sequence by adding the minimum number of '(' at the beginning of the string and ')' at the end of the string. Examples: Input: str = ")))()" Output: "((()))()" Input: str = "())())(())())" Output: "(((())())(())())" Method 1: Approach: Initialize an empty stack.Iterate
13 min read
Find original sequence from Array containing the sequence merged many times in order
Given a number N and an array arr[] that consist of merging N length sequence of distinct integers any number of times maintaining the relative order of elements in the initial sequence. The task is to find the initial sequence of length N maintaining the right order. Examples: Input: N = 4, arr[] = {1, 13, 1, 24, 13, 24, 2, 2}Output: 1 13 24 2 Exp
10 min read
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string. Note: There can be more than one valid sequence, print any of them. Examples: Input: S = "()()()", K = 4Output: ()()Explanation:The string "()()" is a subse
7 min read
Generate a sequence X from given sequence Y such that Yi = gcd(X1, X2 , ... , Xi)
Given a sequence Y of size N where: Yi = gcd(X1, X2, X3, . . ., Xi ) of some sequence X. The task is to find such a sequence X if any such X is possible. Note: If X exists there can be multiple value possible for X. Generating any one is sufficient. Examples: Input: N = 2, Y = [4, 2]Output: [4, 2]Explanation: Y0 = gcd(X0) = X0 = 4. And gcd(4, 2) =
7 min read
k-th missing element in increasing sequence which is not present in a given sequence
Given two sequences, one is increasing sequence a[] and another a normal sequence b[], find the K-th missing element in the increasing sequence which is not present in the given sequence. If no k-th missing element is there output -1 Examples: Input: a[] = {0, 2, 4, 6, 8, 10, 12, 14, 15}; b[] = {4, 10, 6, 8, 12}; k = 3 Output: 14 Explanation : The
6 min read
Nth term of a sequence formed by sum of current term with product of its largest and smallest digit
Given two numbers N and K, where K represents the starting term of the sequence. The task is to find the Nth term of a sequence formed by sum of current term with product of largest and smallest digit of current term, i.e., AN+1 = AN + max(digits of AN) * min(digits of AN) Examples: Input: K = 1, N = 5 Output: 50 Explanation: A1 = 1 A2 = A1 + minDi
6 min read
Lexicographically largest N-length Bitonic sequence made up of elements from given range
Given three integers N, low and high, the task is to find the lexicographically largest bitonic sequence consisting of N elements lying in the range [low, high]. If it is not possible to generate such a sequence, then print "Not Possible". Examples: Input: N = 5, low = 2, high = 6Output: 5 6 5 4 3Explanation:The sequence {arr[0], arr[1]} is strictl
8 min read
Lexicographically largest sub-sequence of the given string
Given string str containing lowercase characters, the task is to find the lexicographically largest sub-sequence of str. Examples: Input: str = "abc" Output: c All possible sub-sequences are "a", "ab", "ac", "b", "bc" and "c" and "c" is the largest among them (lexicographically) Input: str = "geeksforgeeks" Output: ss Approach: Let mx be the lexico
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg