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

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]