Lexicographically smallest permutation of size A having B integers exceeding all preceeding integers

Given two positive integers, A and B, the task is to generate the lexicographically smallest permutation of all integers up to A in which exactly B integers are greater than all its preceding elements.

Examples:

Input: A = 3, B = 2
Output : [1, 3, 2]
Explanation:
All possible permutations of integers [1, 3] are [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]. Out of these permutations, three permutations {(1, 3, 2), (2, 1, 3), (2, 3, 1)} satisfy the necessary condition. The lexicographically smallest permutation of the three is (1, 3, 2).

Input: A = 4, B = 4
Output: [1, 2, 3, 4]

Approach: Follow the steps below to solve the problem:



  1. Generate all possible permutations of integers from [1, A] using inbuilt function permutations() from the itertools library. Basically, it returns a tuple consisting of all possible permutations.
  2. Now, check if the array’s maximum element and the number of elements should satisfy the problem’s condition count is equal or not.
  3. If equal then there is only one possible list of elements that satisfy the condition. Logically they are simply the range of A number of integers starting from 1 in sorted order.
  4. If not, take each tuple from the permutations list and then calculate the number of integers that are present in the tuple which is greater than all the previous integers in that tuple.
  5. If the count is equal to B then load that tuple to another new list.
  6. Test the lists of elements that are loaded by a new list whether they ordered in lexicographically or not if not ordered then arrange them manually and return the minimum of it.

Below is the implementation of the above approach:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
from itertools import permutations
 
# Function to find lexicographically
# smallest permutation of [1, A]
# having B integers greater than
# all the previous elements
 
def getSmallestArray(A, B):
 
    # if A and B are equal
    if A == B:
        return list(range(1, A + 1))
 
    # Initialize pos_list to store list
    # of elements which are satisfying
    # the given conditions
    pos_list = []
 
    # List to store all possible permutations
    Main_List = list(permutations(range(1, A + 1), A))
 
    # Check all the permutations for
    # the given condition
    for L in Main_List:
 
        # Stores the count of elements
        # greater than all the previous
        # elements
        c = 0
 
        i = 0
        j = 1
        while j <= (len(L)-1):
 
            if L[j] > L[i]:
                i += 1
 
            elif i == j:
                c += 1
                j += 1
                i = 0
 
            else:
                j += 1
                i = 0
 
        # If count is equal to B
        if (c + 1) == B:
 
            pos_list.append(list(L))
 
    # If only one tuple satisfies
    # the given condition
    if len(pos_list) == 1:
 
        return pos_list[0]
 
    # Otherwise
    satisfied_list = []
    for i in pos_list:
 
        array_test = ''.join(map(str, i))
        satisfied_list.append(int(array_test))
 
        # Evaluate lexicographically smallest tuple
    small = min(satisfied_list)
    str_arr = list(str(small))
    ans = list(map(int, str_arr))
 
    # Return the answer
    return ans
 
 
# Driver Code
 
A = 3
B = 2
 
print(getSmallestArray(A, B))

chevron_right


Output: 

[1, 3, 2]









 

Time Complexity: O(N2)
Auxiliary Space: O(N2)

Efficient Approach: Follow the steps below to optimize the above approach:

  1. Initialize an array arr[] consisting of first A natural numbers sequentially.
  2. Create a resultant array ans[] and append the first (B – 1) elements from arr[].
  3. So the resultant array have (B – 1) elements that satisfy the given condition.
  4. Now insert the maximum element from arr[] into the resultant array. Remove the inserted elements arr[]
  5. Since we already have B elements , the resultant array have B elements that satisfy the given condition.
  6. Now, copy all remaining elements from arr[] one by one to the resultant array and print the resultant array.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to find lexicographically
// smallest permutation of [1, A]
// having B integers greater than
// all the previous elements
vector<int> getSmallestArray(int A, int B)
{
     
    // Initial array
    vector<int>arr(A);
    for(int i = 0; i < A; i++)
        arr[i] = i + 1;
         
    // Resultant array
    vector<int>ans(A);
 
    // Append the first (B-1) elements
    // to the resultant array 
    for(int i = 0; i < B - 1; i++)
        ans[i] = arr[i];
         
    // Append the maximum from the
    // initial array 
    ans[B - 1] = arr[A - 1];
     
    // Copy the remaining elements 
    for(int i = B; i < A; i++)
        ans[i] = arr[i - 1];
         
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    int A = 3;
    int B = 2;
     
    vector<int>ans = getSmallestArray(A, B);
     
    for(auto i : ans)
        cout << i << " ";
}
 
// This code is contributed by Stream_Cipher

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find lexicographically
// smallest permutation of [1, A]
// having B integers greater than
// all the previous elements
@SuppressWarnings("unchecked")
static void getSmallestArray(int A, int B)
{
     
    // Initial array
    Vector arr = new Vector();
    for(int i = 0; i < A; i++)
        arr.add(i + 1);
         
    // Resultant array
    Vector ans = new Vector();
 
    // Append the first (B-1) elements
    // to the resultant array 
    for(int i = 0; i < B - 1; i++)
        ans.add(arr.get(i));
         
    // Append the maximum from the
    // initial array 
    ans.add(arr.get(A - 1));
     
    // Copy the remaining elements 
    for(int i = B; i < A; i++)
        ans.add(arr.get(i - 1));
         
    // Print the answer
    for(int i = 0; i < ans.size(); i++)
        System.out.print(ans.get(i) + " ");
}
 
// Driver Code
public static void main(String args[])
{
    int A = 3;
    int B = 2;
     
    getSmallestArray(A, B);
}
}
 
// This code is contributed by Stream_Cipher

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to find lexicographically
# smallest permutation of [1, A]
# having B integers greater than
# all the previous elements
 
def getSmallestArray(A, B):
 
    # Initial array
    arr = (list(range(1, (A + 1))))
 
    # Resultant array
    ans = []
 
    # Append the first (B-1) elements
    # to the resultant array
    ans[0:B-1] = arr[0:B-1]
 
    # Delete the appended elements
    # from the initial array
    del arr[0:B-1]
 
    # Append the maximum from the
    # initial array
    ans.append(arr[-1])
 
    # Delete the appended maximum
    del arr[-1]
 
    # Copy the remaining elements
    ans[B:] = arr[:]
 
    # Return the answer
    return ans
 
# Driver Code
 
A = 3
B = 2
 
print(getSmallestArray(A, B))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System.Collections.Generic;
using System;
 
class GFG{
 
// Function to find lexicographically
// smallest permutation of [1, A]
// having B integers greater than
// all the previous elements
 static void getSmallestArray(int A, int B)
{
     
    // Initial array
    List<int> arr = new List<int>();
    for(int i = 0; i < A; i++)
        arr.Add(i + 1);
         
    // Resultant array
    List<int> ans = new List<int>();
 
    // Append the first (B-1) elements
    // to the resultant array 
    for(int i = 0; i < B - 1; i++)
        ans.Add(arr[i]);
         
    // Append the maximum from the
    // initial array 
    ans.Add(arr[A - 1]);
     
    // Copy the remaining elements 
    for(int i = B; i < A; i++)
        ans.Add(arr[i - 1]);
         
    // Print the answer
    for(int i = 0; i < A; i++)
        Console.Write(ans[i] + " ");
}
 
// Driver Code
public static void Main()
{
    int A = 3;
    int B = 2;
     
    getSmallestArray(A,B);
}
}
 
// This code is contributed by Stream_Cipher

chevron_right


Output: 

[1, 3, 2]









 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Stream_Cipher