Leetcode 2924: Find Champion II

grid47
grid47
Exploring patterns and algorithms
Jan 19, 2024 5 min read

In a tournament, there are ’n’ teams numbered from 0 to n-1, where each team is represented as a node in a Directed Acyclic Graph (DAG). You are given an integer ’n’ and a 2D integer array ’edges’, where each element edges[i] = [ui, vi] indicates a directed edge from team ‘ui’ to team ‘vi’, meaning team ‘ui’ is stronger than team ‘vi’. A team will be the champion of the tournament if no other team is stronger than it. If there is exactly one champion, return its index; otherwise, return -1.
Problem
Approach
Steps
Complexity
Input: You are given two inputs: an integer 'n' representing the number of teams, and a 2D integer array 'edges' where each element defines a directed edge between two teams.
Example: For n = 3 and edges = [[0, 1], [1, 2]], the result will be 0.
Constraints:
• 1 <= n <= 100
• m == edges.length
• 0 <= m <= 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 there are no cycles in the graph.
Output: Return the index of the champion team if there is exactly one champion; otherwise, return -1.
Example: For n = 4 and edges = [[0, 2], [1, 3], [1, 2]], the output will be -1.
Constraints:
• The output will either be a valid team index or -1 if no unique champion exists.
Goal: The goal is to find the team that has no incoming edges, meaning no other team is stronger than it. If more than one team has no incoming edges, return -1.
Steps:
• Compute the indegree (number of incoming edges) for each team.
• Check how many teams have zero indegree.
• If exactly one team has zero indegree, that is the champion. Otherwise, return -1.
Goal: The graph is a Directed Acyclic Graph (DAG), meaning there are no cycles. The input size will be reasonable, with 'n' up to 100 teams.
Steps:
• The graph will be acyclic and the number of edges will not exceed n * (n - 1) / 2.
Assumptions:
• The input will be valid and follow the constraints specified.
Input: Example 1: n = 3, edges = [[0, 1], [1, 2]]
Explanation: In this case, team 0 is stronger than team 1, and team 1 is stronger than team 2. Therefore, team 0 is the champion because it has no incoming edges.

Input: Example 2: n = 4, edges = [[0, 2], [1, 3], [1, 2]]
Explanation: Here, both teams 0 and 1 have no incoming edges, meaning there is no unique champion. Therefore, the result is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus