Find Champion II - Count Nodes with Zero Indegree [JS]
Solution: Count Nodes with Zero Indegree
Count the indegrees of each node.
There should be exactly one node with an indegree of zero.
n = number of nodes
, m = number of edges
Time Complexity: O(n + m)
Space Complexity: O(n)
var findChampion = function(n, edges) {
let indegrees = Array(n).fill(0);
for (let [_a, b] of edges) {
indegrees[b]++;
}
let championCount = 0, champion = -1;
for (let i = 0; i < n; i++) {
if (indegrees[i] === 0) {
championCount++;
champion = i;
}
}
return championCount === 1 ? champion : -1;
};
Comments
Post a Comment