Open In App

Print k different sorted permutations of a given array

Last Updated : 22 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] containing N integers, the task is to print k different permutations of indices such that the values at those indices form a non-decreasing sequence. Print -1 if it is not possible.

Examples: 

Input: arr[] = {1, 3, 3, 1}, k = 3 
Output: 
0 3 1 2 
3 0 1 2 
3 0 2 1 
For every permutation, the values at the indices form the following sequence {1, 1, 3, 3}
Input: arr[] = {1, 2, 3, 4}, k = 3 
Output: -1 
There is only 1 non decreasing sequence possible {1, 2, 3, 4}. 

Approach: Sort the given array and keep track of the original indices of each element. That gives one required permutation. Now if any 2 continuous elements are equal then they can be swapped to get another permutation. Similarly, the third permutation can be generated.

Below is the implementation of the above approach: 

C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

int next_pos = 1;
// Utility function to print the original indices
// of the elements of the array
void printIndices(int n, pair<int, int> a[])
{
    for (int i = 0; i < n; i++)
        cout << a[i].second << " ";
    cout << endl;
}

// Function to print the required permutations
void printPermutations(int n, int a[], int k)
{

    // To keep track of original indices
    pair<int, int> arr[n];
    for (int i = 0; i < n; i++) 
    {
        arr[i].first = a[i];
        arr[i].second = i;
    }

    // Sort the array
    sort(arr, arr + n);

    // Count the number of swaps that can
    // be made
    int count = 1;
    for (int i = 1; i < n; i++)
        if (arr[i].first == arr[i - 1].first)
            count++;

    // Cannot generate 3 permutations
    if (count < k) {
        cout << "-1";
        return;
    }

    for (int i = 0; i < k - 1; i++) 
    {
        // Print the first permutation
        printIndices(n, arr);

        // Find an index to swap and create
        // second permutation
        for (int j = next_pos; j < n; j++) 
        {
            if (arr[j].first == arr[j - 1].first) 
            {
                swap(arr[j], arr[j - 1]);
                next_pos = j + 1;
                break;
            }
        }
    }

    // Print the last permutation
    printIndices(n, arr);
}

// Driver code
int main()
{
    int a[] = { 1, 3, 3, 1 };
    int n = sizeof(a) / sizeof(a[0]);

    int k = 3;
  
    // Function call
    printPermutations(n, a, k);

    return 0;
}
Java Python3 C# JavaScript

Output
0 3 1 2 
3 0 1 2 
3 0 2 1 

Time Complexity: O(N log N + K N)
 


Next Article

Similar Reads