Minimum Swaps to Arrange a Binary Grid LeetCode solution in JavaScript

1
var minSwaps = function (grid) {
2
const arr = [];
3
let count = 0;
4

5
for (let row of grid) {
6
arr.push(row.lastIndexOf(1));
7
}
8

9
function swap(i, j) {
10
[arr[i], arr[j]] = [arr[j], arr[i]];
11
count++;
12
}
13

14
for (let i = 0; i < arr.length; i++) {
15
// if num <= i pass b/c it's its correct spot
16
if (arr[i] <= i) continue;
17
let j = i;
18

19
// scan forward looking for a num <= i
20
while (arr[j] > i) {
21
j++;
22
if (j >= arr.length) return -1;
23
}
24

25
// swap as you move back to the right spot
26
for (let k = j; k > i; k--) {
27
swap(k, k - 1);
28
}
29
}
30
return count;
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0