Couples Holding Hands LeetCode solution in Java

1
class Solution {
2
public int minSwapsCouples(int[] row) { // Union -Find pairs for 2
3
Map<Integer, Integer> parents = new HashMap<>();
4
int count = 0;
5
for (int i = 0; i < row.length; i += 2) {
6
int parent = Math.min(row[i], row[i + 1]);
7
int child = Math.max(row[i], row[i + 1]);
8
parents.put(parent, child);
9
}
10
for (int i = 0; i < row.length; i += 2) {
11
if ((parents.containsKey(i) && parents.get(i) == (i + 1))
12
|| (parents.containsKey(i - 1) && parents.get(i - 1) == i)) continue;
13
count += 1;
14
int curChild = parents.get(i);
15
int correctChildsChild = parents.get(i + 1);
16
parents.remove(i + 1); // remove mapping of 1 in eg) //0,2 ; 1,3
17
parents.put(Math.min(curChild, correctChildsChild), Math.max(curChild, correctChildsChild));
18
// add mapping 2->7 , also place smaller number as parent for eg)//0,4 ; 1,3
19
parents.put(i, i + 1);
20
}
21
return count;
22
}
23
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0