Most Stones Removed with Same Row or Column LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} stones
3
* @return {number}
4
*/
5
var removeStones = function (stones) {
6
const n = stones.length;
7
// initial number of components(a.k.a island)
8
let numComponents = n;
9

10
//initial forest for union find
11
let forest = new Array(n).fill(0).map((ele, index) => index);
12

13
// recursively finding the root of rarget node
14
const find = (a) => {
15
if (forest[a] === a) {
16
return a;
17
}
18
return find(forest[a]);
19
};
20

21
// function for uniting two stones
22
const union = (a, b) => {
23
const rootA = find(a);
24
const rootB = find(b);
25
if (rootA != rootB) {
26
//connect their roots if currently they are not connected
27
forest[rootA] = rootB;
28
//subtract the number of islands by one since two islands are connected now
29
numComponents -= 1;
30
}
31
};
32

33
for (let i = 0; i < stones.length - 1; i++) {
34
for (let j = i + 1; j < stones.length; j++) {
35
// if two stones are connected(i.e. share same row or column), unite them
36
if (stones[i][0] === stones[j][0] || stones[i][1] === stones[j][1]) {
37
union(i, j);
38
}
39
}
40
}
41

42
// this is the most confusing part.
43
// The number of stones can be removed is not equal to the number of islands.
44
// e.g. we have two islands with total of 10 stores, each island will leave one extra stone after the
45
// removal, therefore we can remove 10 - 2 = 8 stones in total
46
return n - numComponents;
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0