#2924

Find Champion II

Medium
Graph TheoryGraph TraversalTopological Sorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

In the optimal solution, we utilize the property of a Directed Acyclic Graph (DAG) where the champion must have an in-degree of 0. This allows us to efficiently determine the champion by counting incoming edges for each team.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an array to count in-degrees for each team.
  2. 2Step 2: Iterate through the edges and update the in-degree count for each team.
  3. 3Step 3: Identify teams with in-degree 0 and store them in a list.
  4. 4Step 4: If there's exactly one team with in-degree 0, return that team; otherwise, return -1.
solution.py6 lines
1def findChampion(n, edges):
2    in_degree = [0] * n
3    for u, v in edges:
4        in_degree[v] += 1
5    champions = [i for i in range(n) if in_degree[i] == 0]
6    return champions[0] if len(champions) == 1 else -1

Complexity note: The time complexity is O(n + m) because we traverse all edges and nodes once. The space complexity is O(n) for storing the in-degree counts.

  • 1A champion must have an in-degree of 0 in a DAG.
  • 2If multiple teams have an in-degree of 0, there is no unique champion.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.