[LeetCode] Minimum Adjacent Swaps to Reach the Kth Smallest Number

1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number

You are given a string num, representing a large integer, and an integer k.

We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.

  • For example, when num = “5489355142”:
  • The 1st smallest wonderful integer is “5489355214”.
  • The 2nd smallest wonderful integer is “5489355241”.
  • The 3rd smallest wonderful integer is “5489355412”.
  • The 4th smallest wonderful integer is “5489355421”.

Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.

The tests are generated in such a way that kth smallest wonderful integer exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int getMinSwaps(string num, int k) {
string target = num;
while(k--) next_permutation(begin(target), end(target));
int res = 0, pos = 0;
while(num != target) {
if(num[pos] != target[pos]) {
int find = target.find(num[pos], pos);
while(find != pos) {
swap(target[find], target[find - 1]);
res++;
find--;
}
}
pos++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/02/PS/LeetCode/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.