-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1536-minimum-swaps-to-arrange-a-binary-grid.js
More file actions
78 lines (70 loc) · 1.99 KB
/
1536-minimum-swaps-to-arrange-a-binary-grid.js
File metadata and controls
78 lines (70 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Minimum Swaps to Arrange a Binary Grid
* Time Complexity: O(n^3)
* Space Complexity: O(n)
*/
var minSwaps = function (grid) {
const gridSize = grid.length;
const trailingZeroCountsArray = new Array(gridSize);
const calculateTrailingZerosForRow = (
currentGridReference,
currentGridRowIdentifier,
) => {
let currentTrailingZeroValue = 0;
let columnScanningIndex = gridSize - 1;
while (columnScanningIndex >= 0) {
if (
currentGridReference[currentGridRowIdentifier][columnScanningIndex] ===
0
) {
currentTrailingZeroValue++;
} else {
break;
}
columnScanningIndex--;
}
return currentTrailingZeroValue;
};
for (let primaryRowIndex = 0; primaryRowIndex < gridSize; primaryRowIndex++) {
trailingZeroCountsArray[primaryRowIndex] = calculateTrailingZerosForRow(
grid,
primaryRowIndex,
);
}
let totalSwapOperations = 0;
for (
let targetPositionIndex = 0;
targetPositionIndex < gridSize - 1;
targetPositionIndex++
) {
const minimumRequiredZeros = gridSize - 1 - targetPositionIndex;
let foundAcceptableRow = false;
for (
let currentScanningIndex = targetPositionIndex;
currentScanningIndex < gridSize;
currentScanningIndex++
) {
if (
trailingZeroCountsArray[currentScanningIndex] >= minimumRequiredZeros
) {
foundAcceptableRow = true;
for (
let bubbleUpCounter = currentScanningIndex;
bubbleUpCounter > targetPositionIndex;
bubbleUpCounter--
) {
let temporaryExchangeValue = trailingZeroCountsArray[bubbleUpCounter];
trailingZeroCountsArray[bubbleUpCounter] =
trailingZeroCountsArray[bubbleUpCounter - 1];
trailingZeroCountsArray[bubbleUpCounter - 1] = temporaryExchangeValue;
totalSwapOperations++;
}
break;
}
}
if (!foundAcceptableRow) {
return -1;
}
}
return totalSwapOperations;
};