Couples Holding Hands LeetCode solution in JavaScript

1
/**
2
* @param {number[]} row
3
* @return {number}
4
*/
5
var minSwapsCouples = function (row) {
6
let currentPositions = [];
7

8
for (let i = 0; i < row.length; i++) {
9
currentPositions[row[i]] = i;
10
}
11

12
let swapCount = 0;
13

14
for (
15
let j = 0;
16
j < row.length;
17
j += 2 // Looping through the couches
18
) {
19
let leftPartner = row[j];
20
let correctRightPartner = getPartner(leftPartner);
21
if (row[j + 1] !== correctRightPartner) {
22
console.log("unhappy");
23
//Swap Positions of positions - Bring the Correct Right Partner in the Couch
24
let tempValue = row[j + 1];
25
row[j + 1] = correctRightPartner;
26
let tempPosition = currentPositions[correctRightPartner];
27
row[tempPosition] = tempValue;
28

29
//Correct the Hash Table keeping the currentPositions of each Person.
30
currentPositions[correctRightPartner] = j + 1;
31
currentPositions[tempValue] = tempPosition;
32

33
swapCount += 1;
34
} else {
35
console.log("happy");
36
}
37
}
38

39
console.log("currentPositions", currentPositions, "Correct Row", row);
40

41
return swapCount;
42
};
43
function getPartner(x) {
44
if (x % 2 === 0) {
45
return x + 1;
46
} else return x - 1;
47
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0