Minimum Possible Integer After at Most K Adjacent Swaps On Digits LeetCode solution in JavaScript

1
/**
2
* @param {string} num
3
* @param {number} k
4
* @return {string}
5

6
Idea is based on bubble sorting with limited steps k
7

8
*/
9

10
var minInteger = function (num, k) {
11
if (num.length == 1) return num;
12

13
let nums = num.split("");
14
let i = 0,
15
j = 0;
16

17
while (k && i < num.length - 1) {
18
// step 0: if leading zero, check the next digit
19
if (nums[i] == "0") {
20
i++;
21
j++;
22
continue;
23
}
24

25
// step 1: find the min digit
26
let p = j,
27
steps = 0;
28
while (nums[p] !== "0" && j < nums.length && steps <= k) {
29
if (nums[j] < nums[p]) p = j;
30
j++;
31
steps++;
32
}
33

34
// step 2: nums[i] is the current minimum digit --> check next digit
35
if (p == i) {
36
i++;
37
j = i;
38
continue;
39
}
40

41
// step 3: move the min digit to i
42
for (; p > i; p--) {
43
[nums[p], nums[p - 1]] = [nums[p - 1], nums[p]];
44
k--;
45
}
46

47
i++;
48
j = i;
49
}
50

51
return nums.join("");
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0