Open In App

Permute the elements of an array following given order

Last Updated : 25 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A permutation is a rearrangement of members of a sequence into a new sequence. For example, there are 24 permutations of [a, b, c, d]. Some of them are [b, a, d, c], [d, a, b, c] and [a, d, b, c]
A permutation can be specified by an array P[] where P[i] represents the location of the element at index i in the permutation.
For example, the array [3, 2, 1, 0] represents the permutation that maps the element at index 0 to index 3, the element at index 1 to index 2, the element at index 2 to index 1 and the element at index 3 to index 0.
Given the array arr[] of N elements and a permutation array P[], the task is to permute the given array arr[] based on the permutation array P[].
Examples: 
 

Input: arr[] = {1, 2, 3, 4}, P[] = {3, 2, 1, 0} 
Output: 4 3 2 1
Input: arr[] = {11, 32, 3, 42}, P[] = {2, 3, 0, 1} 
Output: 3 42 11 32 
 

Approach: Every permutation can be represented by a collection of independent permutations, each of which is cyclic i.e. it moves all the elements by a fixed offset wrapping around. To find and apply the cycle that indicates entry i, just keep going forward (from i to P[i]) till we get back at i. After completing the current cycle, find another cycle that has not yet been applied. To check this, subtract n from P[i] after applying it. This means that if an entry in P[i] is negative, we have performed the corresponding move.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to permute the given
// array based on the given conditions
int permute(int A[], int P[], int n)
{
    // For each element of P
    for (int i = 0; i < n; i++) {
        int next = i;
 
        // Check if it is already
        // considered in cycle
        while (P[next] >= 0) {
 
            // Swap the current element according
            // to the permutation in P
            swap(A[i], A[P[next]]);
            int temp = P[next];
 
            // Subtract n from an entry in P
            // to make it negative which indicates
            // the corresponding move
            // has been performed
            P[next] -= n;
            next = temp;
        }
    }
}
 
// Driver code
int main()
{
    int A[] = { 5, 6, 7, 8 };
    int P[] = { 3, 2, 1, 0 };
    int n = sizeof(A) / sizeof(int);
 
    permute(A, P, n);
 
    // Print the new array after
    // applying the permutation
    for (int i = 0; i < n; i++)
        cout << A[i] << " ";
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
 
// Function to permute the given
// array based on the given conditions
static void permute(int A[], int P[], int n)
{
    // For each element of P
    for (int i = 0; i < n; i++)
    {
        int next = i;
 
        // Check if it is already
        // considered in cycle
        while (P[next] >= 0)
        {
 
            // Swap the current element according
            // to the permutation in P
            swap(A, i, P[next]);
            int temp = P[next];
 
            // Subtract n from an entry in P
            // to make it negative which indicates
            // the corresponding move
            // has been performed
            P[next] -= n;
            next = temp;
        }
    }
}
 
static int[] swap(int []arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
}
 
// Driver code
public static void main(String[] args)
{
    int A[] = { 5, 6, 7, 8 };
    int P[] = { 3, 2, 1, 0 };
    int n = A.length;
 
    permute(A, P, n);
 
    // Print the new array after
    // applying the permutation
    for (int i = 0; i < n; i++)
        System.out.print(A[i]+ " ");
 
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python 3 implementation of the approach
 
# Function to permute the given
# array based on the given conditions
def permute(A, P, n):
     
    # For each element of P
    for i in range(n):
        next = i
 
        # Check if it is already
        # considered in cycle
        while (P[next] >= 0):
             
            # Swap the current element according
            # to the permutation in P
            t = A[i]
            A[i] = A[P[next]]
            A[P[next]] = t
             
            temp = P[next]
 
            # Subtract n from an entry in P
            # to make it negative which indicates
            # the corresponding move
            # has been performed
            P[next] -= n
            next = temp
 
# Driver code
if __name__ == '__main__':
    A = [5, 6, 7, 8]
    P = [3, 2, 1, 0]
    n = len(A)
 
    permute(A, P, n)
 
    # Print the new array after
    # applying the permutation
    for i in range(n):
        print(A[i], end = " ")
         
# This code is contributed by Surendra_Gangwar


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to permute the given
    // array based on the given conditions
    static void permute(int []A, int []P, int n)
    {
        // For each element of P
        for (int i = 0; i < n; i++)
        {
            int next = i;
     
            // Check if it is already
            // considered in cycle
            while (P[next] >= 0)
            {
     
                // Swap the current element according
                // to the permutation in P
                swap(A, i, P[next]);
                int temp = P[next];
     
                // Subtract n from an entry in P
                // to make it negative which indicates
                // the corresponding move
                // has been performed
                P[next] -= n;
                next = temp;
            }
        }
    }
     
    static int[] swap(int []arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return arr;
    }
     
    // Driver code
    public static void Main()
    {
        int []A = { 5, 6, 7, 8 };
        int []P = { 3, 2, 1, 0 };
        int n = A.Length;
     
        permute(A, P, n);
     
        // Print the new array after
        // applying the permutation
        for (int i = 0; i < n; i++)
            Console.Write(A[i]+ " ");
     
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// JavaScript implementation of the approach
 
// Function to permute the given
// array based on the given conditions
function permute(A, P, n) {
    // For each element of P
    for (let i = 0; i < n; i++) {
        let next = i;
 
        // Check if it is already
        // considered in cycle
        while (P[next] >= 0) {
 
            // Swap the current element according
            // to the permutation in P
            let x = A[i];
            A[i] = A[P[next]];
            A[P[next]] = x;
 
            let temp = P[next];
 
            // Subtract n from an entry in P
            // to make it negative which indicates
            // the corresponding move
            // has been performed
            P[next] -= n;
            next = temp;
        }
    }
}
 
// Driver code
 
let A = [5, 6, 7, 8];
let P = [3, 2, 1, 0];
let n = A.length;
 
permute(A, P, n);
 
// Print the new array after
// applying the permutation
for (let i = 0; i < n; i++)
    document.write(A[i] + " ");
     
</script>


Output: 

8 7 6 5

 

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



Similar Reads

Permute two arrays such that sum of every pair is greater or equal to K
Given two arrays of equal size n and an integer k. The task is to permute both arrays such that sum of their corresponding element is greater than or equal to k i.e a[i] + b[i] &gt;= k. The task is to print "Yes" if any such permutation exists, otherwise print "No". Examples : Input : a[] = {2, 1, 3}, b[] = { 7, 8, 9 }, k = 10. Output : Yes Permuta
7 min read
Permute a string by changing case
Print all permutations of a string keeping the sequence but changing cases. Examples: Input : abOutput : AB Ab ab aBInput : ABCOutput : abc Abc aBc ABc abC AbC aBC ABCMethod 1 (Naive) : Naive approach would be to traverse the whole string and for every character, consider two cases, (1) change case and recur (2) Do not change case and recur. [GFGTA
7 min read
Generate elements of the array following given conditions
Given an integer N, for every integer i in the range 2 to N, assign a positive integer [Tex]a_i [/Tex]such that the following conditions hold : For any pair of indices (i, j), if i and j are coprime then [Tex]a_i \neq a_j [/Tex].The maximum value of all [Tex]a_i [/Tex]should be minimized (i.e. max value should be as small as possible). A pair of in
6 min read
Create Y[] by given Array X[] following given condition
Given an array X[] of length N, Where (1 ? Xi ? N). Create an array Y[], where the element at Y[i] should divide an element present at Y[X[i]-1]. and (X[i]-1) is the maximum such position in which the element is divisible by Y[i]. Note: If there are multiple possible arrays Y[]. Then print any one of them. Examples: Input: N = 5, X[] = {5, 2, 3, 4,
4 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11
9 min read
Count of array elements whose order of deletion precedes order of insertion
Given an initial array, A[] and a final array B[] both of size N containing integers from the range [1, N], where A[] represent the order in which elements were inserted and B[] represents the order in which they were removed, the task is to find the number of elements in B[] lying at an index earlier than its respective position in A[]. Examples:
7 min read
Minimum divisions to reduce N to 1 by following given conditions
Given an integer N, the task is to find the minimum number of divisions required to reduce the number to 1 when the divisions follow the given criteria: Pick two integers X and Y such that X+Y is even.Replace N with N/XY where XY is a divisor of N Note: If it is impossible to reduce N to 1, then return -1. Examples: Input: N = 35Output: 1Explanatio
7 min read
Construct a binary string following the given constraints
Given three integers A, B and X. The task is to construct a binary string str which has exactly A number of 0's and B number of 1's provided there has to be at least X indices such that str[i] != str[i+1]. Inputs are such that there's always a valid solution. Examples: Input: A = 2, B = 2, X = 1 Output: 1100 There are two 0's and two 1's and one (=
7 min read
Get last node of the binary tree following given pattern starting from X
Given a binary tree, target node X and a string pattern. The task is to find the last node of the binary tree following the pattern starting from X. Pattern may contain only five types of character 'p', 'l', 'r', 'm' and 'n'. For any character encountered: p: Get to the parent of the current node.l: Get to the left child of the current node.r: Get
17 min read
Maximise matrix sum by following the given Path
Given a 2d-matrix mat[][] consisting of positive integers, the task is to find the maximum score we can reach if we have to go to cell mat[0][N - 1] starting from mat[0][0]. We have to cover the matrix in two phases: Phase 1: If we are at cell mat[i][j] then we can only go to cells mat[i][j + 1] or mat[i + 1][j] without changing the phase else we c
9 min read
Practice Tags :