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

• Difficulty Level : Basic
• Last Updated : 19 Nov, 2021

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:

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.

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 ``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());``      ``cout<<``"str = "``<

## C#

 `// C# program for the above approach``using` `System;``class` `GFG {` `    ``static` `char``[] next_permutation(``char``[] array)``    ``{``        ``int` `i = array.Length - 1;``        ``while` `(i > 0 && array[i - 1] >= array[i]) {``            ``i--;``        ``}` `        ``int` `j = array.Length - 1;` `        ``while` `(array[j] <= array[i - 1]) {``            ``j--;``        ``}` `        ``char` `temp = array[i - 1];``        ``array[i - 1] = array[j];``        ``array[j] = temp;` `        ``j = array.Length - 1;` `        ``while` `(i < j) {``            ``temp = array[i];``            ``array[i] = array[j];``            ``array[j] = temp;``            ``i++;``            ``j--;``        ``}` `        ``return` `array;``    ``}` `    ``// Function to find the minimum number``    ``// of swaps required to make the Kth``    ``// smallest string greater than str``    ``static` `void` `minSwapsKthLargest(``string` `str, ``int` `k)``    ``{``        ``// Store the copy of the string``        ``string` `res = str;``        ``char``[] str1 = str.ToCharArray();` `        ``// Find the K-th permutation of``        ``// the given numeric string``        ``for` `(``int` `i = 0; i < k; i++) {``            ``next_permutation(str1);``        ``}` `        ``// 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] != str1[i]) {``                ``int` `start = i + 1;` `                ``// Search from i+1 index``                ``while` `(res[i] != str1[start]) {` `                    ``// Find the index to swap``                    ``start++;``                ``}``                ``while` `(i != start) {``                    ``char` `temp = str1[start];``                    ``str1[start] = str1[start - 1];``                    ``str1[start - 1] = temp;` `                    ``// Swap untill the characters``                    ``// are at same index``                    ``start--;``                    ``swap_count++;``                ``}``            ``}``        ``}` `        ``// Print the minimum number of counts``        ``Console.WriteLine(swap_count);``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``string` `S = ``"11112"``;``        ``int` `K = 4;``        ``minSwapsKthLargest(S, K);``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``
Output:
`4`

Time Complexity: O(N*(N + K))
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up