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

1
var getMinSwaps = function (num, k) {
2
const digits = [...num];
3
const len = digits.length;
4

5
// helper function to swap elements in digits in place
6
const swap = (i, j) => ([digits[i], digits[j]] = [digits[j], digits[i]]);
7

8
// helper function to reverse elements in digits from i to the end of digits
9
const reverse = (i) => {
10
for (let j = len - 1; i < j; ++i && --j) {
11
swap(i, j);
12
}
13
};
14

15
// helper to get the next smallest permutation for digits
16
const nextPermutation = () => {
17
// from right to left, find the first decreasing index
18
// in digits and store it as i
19
let i = len - 2;
20
while (digits[i] >= digits[i + 1]) {
21
i--;
22
}
23

24
// from right to left, find the first index in digits
25
// that is greater than element at i
26
let j = len - 1;
27
while (digits[j] <= digits[i]) {
28
j--;
29
}
30

31
// swap the 2 elements at i and j
32
swap(i, j);
33
// reverse all elements after i because we know that
34
// all elements after i are in ascending order
35
// from right to left
36
reverse(i + 1);
37
};
38

39
// find the next permutation k times
40
for (let i = 0; i < k; i++) {
41
nextPermutation();
42
}
43

44
// find out how many swaps it will take to get to the
45
// kth permutation by finding out how many swaps
46
// it takes to put digits back to its original state
47
let numSwaps = 0;
48
for (let i = 0; i < len; i++) {
49
let j = i;
50
// find the first element in digits to matches
51
// num[i] and hold its place at j
52
while (num[i] !== digits[j]) {
53
j++;
54
}
55

56
// move the element at j to i while counting the
57
// number of swaps
58
while (i < j) {
59
swap(j, j - 1);
60
numSwaps++;
61
j--;
62
}
63
}
64
return numSwaps;
65
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0