Find Champion II - Problem

There are n teams numbered from 0 to n - 1 in a tournament; each team is also a node in a DAG (Directed Acyclic Graph). You are given the integer n and a 0-indexed 2D integer array edges of length m representing the DAG, where edges[i] = [ui, vi] indicates that there is a directed edge from team ui to team vi in the graph.

A directed edge from a to b in the graph means that team a is stronger than team b and team b is weaker than team a.

Team a will be the champion of the tournament if there is no team b that is stronger than team a.

Return the team that will be the champion of the tournament if there is a unique champion, otherwise, return -1.

Input & Output

Example 1 — Basic Tournament
$ Input: n = 3, edges = [[0,1],[1,2]]
Output: 0
💡 Note: Team 0 beats team 1, team 1 beats team 2. Team 0 has no incoming edges, so it's the unique champion.
Example 2 — No Unique Champion
$ Input: n = 4, edges = [[0,2],[1,3],[1,2]]
Output: -1
💡 Note: Both team 0 and team 1 have no incoming edges, so there's no unique champion.
Example 3 — Single Team
$ Input: n = 1, edges = []
Output: 0
💡 Note: Only one team exists with no edges, so team 0 is the champion by default.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ n * (n - 1) / 2
  • edges[i].length == 2
  • 0 ≤ edge[i][j] ≤ n - 1
  • edges[i][0] ≠ edges[i][1]
  • The input is generated such that if team a is stronger than team b, team b is not stronger than team a
  • The input is generated such that if team a is stronger than team b and team b is stronger than team c, then team a is stronger than team c

Visualization

Tap to expand
Find Champion II - In-degree Counting INPUT Tournament DAG (n=3 teams) 0 1 2 stronger stronger n = 3 edges = [[0,1],[1,2]] 0 beats 1, 1 beats 2 ALGORITHM STEPS 1 Initialize In-degrees in_degree[0,1,2] = [0,0,0] 2 Count In-degrees Process each edge [u,v] In-degree Count Table Team: 0 1 2 In-deg: 0 1 1 [0,1] adds 1 to node 1 [1,2] adds 1 to node 2 3 Find Zero In-degree Only team 0 has in_deg=0 4 Check Uniqueness Exactly 1 team: Valid! Multiple: Return -1 FINAL RESULT Champion Found! Team 0 No team is stronger than Team 0 (in-degree = 0) OUTPUT 0 Key Insight: The champion is the team with NO incoming edges (in-degree = 0), meaning no team is stronger. If exactly one team has in-degree 0, return it. If zero or multiple teams have in-degree 0, return -1. TutorialsPoint - Find Champion II | In-degree Counting Approach
Asked in
Amazon 15 Microsoft 12
12.5K Views
Medium Frequency
~15 min Avg. Time
486 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen