Find Champion II

Medium

Topics
Graph

There are n teams labeled 0..n-1 in a tournament. Each directed edge [u, v] means team u is stronger than team v. A team is the champion if no other team is stronger than it. Return the label of the unique champion, or -1 if it is not unique.

Example 1

012
nobody is stronger
An arrow a → b means a is stronger than b. The champion is the unique team with no incoming arrow. Exactly one qualifies, team 0.
Directed edges [stronger, weaker].
Input:  n = 3, edges = [[0,1],[1,2]]
Output: 0

Example 2

01
The champion is the unique team with no incoming arrow. 0 teams have no incoming arrow, so no single champion exists and the answer is -1.
Input:  n = 2, edges = [[0,1],[1,0]]
Output: -1

Constraints

  • 1 <= n <= 100
  • edges[i] = [u, v] with u != v.
Editorial — intuition, approach, complexity and pitfalls

Intuition

An edge a -> b means a is stronger than b. A champion is a team nobody is stronger than — that is, a vertex with in-degree zero. And it is only the champion if it is unique: two teams with no incoming edges means neither can be shown stronger than the other, so there is no definite answer.

So the whole problem is one in-degree tally. No traversal, no topological sort — just count incoming edges and check whether exactly one vertex has none.

Approach

  1. Tally in-degrees over the edge list.
  2. Count vertices with in-degree zero, remembering one of them.
  3. Return it if the count is exactly 1, else -1.

Dry Run

n = 3, edges = [[0,1],[1,2]]
indeg = [0, 1, 1]
exactly one zero, at vertex 0  -> champion 0

n = 4, edges = [[0,2],[1,3],[1,2]]
indeg = [0, 0, 2, 1]
two vertices with in-degree zero (0 and 1) -> -1

n = 2, edges = []
indeg = [0, 0]  -> two candidates -> -1

Complexity

  • Time — O(n + e): one pass over edges, one over vertices.
  • Space — O(n): the in-degree array.

Common Pitfalls

  • Returning the first zero-in-degree vertex without checking uniqueness. Two candidates means -1, and that is the entire difficulty of the problem.
  • Counting out-degree instead, or looking for the vertex with the highest out-degree. A champion is defined by having no superior, not by beating the most teams.
  • Running a topological sort. It works and is far more machinery than one tally.
  • Assuming the graph is connected or acyclic in a way that guarantees a champion. With no edges at all and n > 1, there is none.

Full Solution — all languages

class Solution:
    def findChampion(self, n, edges):
        indeg = [0] * n
        for a, b in edges:
            indeg[b] += 1
        champ, cnt = -1, 0
        for i in range(n):
            if indeg[i] == 0:
                champ = i
                cnt += 1
        return champ if cnt == 1 else -1
SensAI
Beta
Tap the mic to stop voice mode