The Wayback Machine - https://web.archive.org/web/20210507152839/https://www.geeksforgeeks.org/lexicographically-largest-permutation-possible-by-a-swap-that-is-smaller-than-a-given-array/
Skip to content
Related Articles

Related Articles

Lexicographically largest permutation possible by a swap that is smaller than a given array
  • Difficulty Level : Medium
  • Last Updated : 06 May, 2021

Given an array arr[] consisting of N integers, the task is to find the lexicographically largest permutation of the given array possible by exactly one swap, which is smaller than the given array. If it is possible obtain such a permutation, then print that permutation. Otherwise, print “-1”.

Examples:

Input: arr[] = {5, 4, 3, 2, 1} 
Output: 5 4 3 1 2
Explanation:
Lexicographically the largest permutation which is smaller than the given array can be formed by swapping 2 and 1.
Hence, the resultant permutation is {5, 4, 3, 1, 2}

Input: arr[] = {1, 2, 3, 4, 5}
Output: -1

Approach: The given problem can be solved by finding the last element which is greater than its next element, and swap it with the next smaller element in the array. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++




// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to lexicographic largest
// permutation possible by a swap
// that is smaller than given array
void findPermutation(vector<int>& arr)
{
    int N = arr.size();
    int i = N - 2;
  
    // Find the index of first element
    // such that arr[i] > arr[i + 1]
    while (i >= 0 && arr[i] <= arr[i + 1])
        i--;
  
    // If the array is sorted
    // in increasing order
    if (i == -1) {
        cout << "-1";
        return;
    }
  
    int j = N - 1;
  
    // Find the index of first element
    // which is smaller than arr[i]
    while (j > i && arr[j] >= arr[i])
        j--;
  
    // If arr[j] == arr[j-1]
    while (j > i && arr[j] == arr[j - 1]) {
  
        // Decrement j
        j--;
    }
  
    // Swap the element
    swap(arr[i], arr[j]);
  
    // Print the array arr[]
    for (auto& it : arr) {
        cout << it << ' ';
    }
}
  
// Driver Code
int main()
{
    vector<int> arr = { 1, 2, 5, 3, 4, 6 };
    findPermutation(arr);
  
    return 0;
}
Output:
1 2 4 3 5 6

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

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :