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.
1#include <stdio.h>
2#include <stdbool.h>
3
4int findChampion(int n, int edges[][2], int edgesSize) {
5 int inDegree[n];
6 for (int i = 0; i < n; i++) inDegree[i] = 0;
7
8 for (int i = 0; i < edgesSize; i++) {
9 inDegree[edges[i][1]]++;
10 }
11
12 int champion = -1;
13 for (int i = 0; i < n; i++) {
14 if (inDegree[i] == 0) {
15 if (champion == -1) {
16 champion = i;
17 } else {
18 return -1; // More than one champion
19 }
20 }
21 }
22 return champion;
23}
24
25int main() {
26 int edges[][2] = {{0, 1}, {1, 2}};
27 int result = findChampion(3, edges, 2);
28 printf("Champion: %d\n", result);
29 return 0;
30}
31
This C code snippet creates an array to store the in-degree of each team. It iterates over the edges, updating the in-degree of destination nodes. Finally, it checks for nodes with an in-degree of 0. If there's exactly one, it returns this as the champion.
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.
1function topologicalSort(n, adj) {
2 let visited = new Array(n).fill(false);
3 let stack = [];
4
5 function dfs(v) {
6 visited[v] = true;
7 for (let i of adj[v]) {
8 if (!visited[i]) {
9 dfs(i);
10 }
11 }
12 stack.push(v);
13 }
14
15 for (let i = 0; i < n; i++) {
16 if (!visited[i]) {
17 dfs(i);
18 }
19 }
20 return stack;
21}
22
23function findChampion(n, edges) {
24 let adj = Array.from({ length: n }, () => []);
25 for (let [u, v] of edges) {
26 adj[u].push(v);
27 }
28 let stack = topologicalSort(n, adj);
29 let potentialChampion = stack.pop();
30
31 for (let team of stack) {
32 if (!adj[potentialChampion].includes(team))
33 return -1;
34 }
35 return potentialChampion;
36}
37
38console.log(findChampion(3, [[0, 1], [1, 2]]));
39
This JavaScript solution involves topological sorting via DFS, where the last node in the sort order is a candidate for titleholder, subject to verification.