Find Champion II - Count Nodes with Zero Indegree [JS]

Description 

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 nodesm = 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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]