Minimum Degree of a Connected Trio in a Graph LeetCode solution in JavaScript

1
var minTrioDegree = function (n, edges) {
2
// create an adjacency list of all the edges;
3
const adjacencyList = new Array(n + 1).fill(0).map(() => new Set());
4
for (const [x, y] of edges) {
5
adjacencyList[x].add(y);
6
adjacencyList[y].add(x);
7
}
8

9
let minimumDegree = Infinity;
10

11
// Find all the combinations of 3 vertices that connect
12
// and if they connect calculate the degree
13
for (let i = 1; i <= n; i++) {
14
for (let j = i + 1; j <= n; j++) {
15
for (let k = j + 1; k <= n; k++) {
16
if (
17
adjacencyList[i].has(j) &&
18
adjacencyList[i].has(k) &&
19
adjacencyList[j].has(k)
20
) {
21
// We minus 6 because we have 3 vertices and each vertices has 2 edges
22
// going out to the 3 connecting nodes
23
const degree =
24
adjacencyList[i].size +
25
adjacencyList[j].size +
26
adjacencyList[k].size -
27
6;
28
minimumDegree = Math.min(minimumDegree, degree);
29
}
30
}
31
}
32
}
33

34
return minimumDegree === Infinity ? -1 : minimumDegree;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0