Minimum Adjacent Swaps to Reach the Kth Smallest Number LeetCode solution in C++

1
class Solution {
2
public:
3
// GREEDY APPROACH
4
// min steps to make strings equal
5

6
int minSteps(string s1, string s2) {
7
int size = s1.length();
8
int i = 0, j = 0;
9
int result = 0;
10

11
while (i < size) {
12
j = i;
13
while (s1[j] != s2[i]) j++;
14

15
while (i < j) {
16
swap(s1[j], s1[j - 1]);
17
j--;
18
result++;
19
}
20
i++;
21
}
22
return result;
23
}
24

25
int getMinSwaps(string num, int k) {
26
string original = num;
27

28
while (k--) {
29
next_permutation(num.begin(), num.end());
30
}
31

32
return minSteps(original, num);
33
}
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0