The Wayback Machine - https://web.archive.org/web/20211019102609/https://www.geeksforgeeks.org/minimum-adjacent-swaps-required-to-get-kth-smallest-number-greater-than-given-number/
Skip to content
Related Articles

Related Articles

Improve Article

Minimum adjacent swaps required to get Kth smallest number greater than given number

  • Last Updated : 19 Oct, 2021
Geek Week

Given numeric string S of size N and a positive integer K, the task is to find the minimum number of adjacent swaps required in S to obtain the Kth smallest numeric string greater than the given string.

Examples:

Input: S = “11112”, K = 4
Output: 4
Explanation:
The Kth(= 4th) smallest numeric string which is greater than the given string is “21111”. The sequence of adjacent swap to reache the string “21111” is “11112” -> “11121” -> “11211″ -> “12111″ -> “21111″.
Therefore, the minimum number of adacent swaps required is 4.

Input: S = “12345”, K = 1
Output: 1

 

Approach: The given problem can be solved by using the Greedy Approach. Follow the steps below to solve the problem:



  • Store the copy of the current numeric string in a variable, say res.
  • Create a variable, say totalSwaps that stores the minimum swaps required.
  • Since K-th largest number is required, this statement is equal to finding K-th permutation starting from the current string.
  • Find the K-th permutation using the function next_permutation().
  • Iterate over the range [0, N) using the variable i and perform the following tasks:
    • If res[i] is not equal to str[i] then initialize the variable start as i+1 and traverse over a while loop till res[i] is not equal to str[start] and increase the value of i by 1.
    • Iterate a loop till i is not equal to start and swap the values str[start] and str[start – 1] and decrease the value of start by 1 and increase the value of totalSwaps by 1.
  • After performing the above steps, print the value of totalSwaps as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the minimum number
// of swaps required to make the Kth
// smallest string greater than str
void minSwapsKthLargest(string str, int k)
{
    // Store the copy of the string
    string res = str;
  
    // Find the K-th permutation of
    // the given numeric string
    for (int i = 0; i < k; i++) {
        next_permutation(
            str.begin(), str.end());
    }
  
    // Stores the count of swaps required
    int swap_count = 0;
  
    // Traverse the string and find the
    // swaps required greedily
    for (int i = 0; i < res.length(); i++) {
  
        // If both characters do not match
        if (res[i] != str[i]) {
            int start = i + 1;
  
            // Search from i+1 index
            while (res[i] != str[start]) {
  
                // Find the index to swap
                start++;
            }
            while (i != start) {
                swap(str[start], str[start - 1]);
  
                // Swap untill the characters
                // are at same index
                start--;
                swap_count++;
            }
        }
    }
  
    // Print the minimum number of counts
    cout << swap_count;
}
  
// Driver Code
int main()
{
    string S = "11112";
    int K = 4;
    minSwapsKthLargest(S, K);
  
    return 0;
}
Output:
4

Time Complexity: O(N*(N + K))
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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up