In this approach, we calculate the in-degree for each node in the graph. The in-degree of a node is the number of edges that point to it. If a node has an in-degree of 0, it means no other node (team in this case) is stronger than it, making it a candidate for the champion. If exactly one such node exists, it is the unique champion. Otherwise, we return -1.
Time Complexity: O(n + m), where n is the number of nodes and m is the number of edges. Space Complexity: O(n), as we store the in-degree of each node.
1using System;
2
3public class Tournament {
4 public static int FindChampion(int n, int[][] edges) {
5 int[] inDegree = new int[n];
6 foreach (var edge in edges) {
7 inDegree[edge[1]]++;
8 }
9 int champion = -1;
10 for (int i = 0; i < n; i++) {
11 if (inDegree[i] == 0) {
12 if (champion == -1) {
13 champion = i;
14 } else {
15 return -1;
16 }
17 }
18 }
19 return champion;
20 }
21
22 public static void Main() {
23 int[][] edges = { new int[] { 0, 1 }, new int[] { 1, 2 } };
24 Console.WriteLine("Champion: " + FindChampion(3, edges));
25 }
26}
27
This C# approach uses an array to manage node in-degrees and checks for zero in-degree nodes, marking a unique one as the champion if identified.
This approach uses topological sorting to find the last node in the order, presuming no other nodes are stronger. If multiple final nodes exist in the topological order, it implies multiple candidates, hence no unique champion can be determined.
Time Complexity: O(n + m). Space Complexity: O(n^2) due to adjacency matrix used for simplicity.
1#include <stdio.h>
2#include <stdlib.h>
3
4void topologicalSortUtil(int v, int visited[], int *stack, int *index, int adj[][100], int n) {
5 visited[v] = 1;
6 for (int i = 0; i < n; i++) {
7 if (adj[v][i] && !visited[i]) {
8 topologicalSortUtil(i, visited, stack, index, adj, n);
9 }
10 }
11 stack[(*index)--] = v;
12}
13
14int topologicalSort(int n, int edges[][2], int edgesSize) {
15 int adj[100][100] = {0};
16 for (int i = 0; i < edgesSize; i++) {
17 adj[edges[i][0]][edges[i][1]] = 1;
18 }
19 int visited[100] = {0};
20 int stack[100];
21 int index = n - 1;
22 for (int i = 0; i < n; i++) {
23 if (!visited[i])
24 topologicalSortUtil(i, visited, stack, &index, adj, n);
25 }
26 int potentialChampion = stack[n - 1];
27 for (int i = 0; i < n - 1; i++) {
28 if (!adj[potentialChampion][stack[i]])
29 return -1;
30 }
31 return potentialChampion;
32}
33
34int main() {
35 int edges[][2] = {{0, 1}, {1, 2}};
36 int result = topologicalSort(3, edges, 2);
37 printf("Champion: %d\n", result);
38 return 0;
39}
40
This C implementation uses DFS for topological sorting to find the potential champion, verifying it by checking if it's stronger than all other remaining teams.