LeetCode 2924: Find Champion II Solution
Master LeetCode problem 2924 (Find Champion II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2924. Find Champion II
Problem Explanation
Explanation
To solve this problem, we can build a directed graph based on the edges provided and then perform a topological sorting. After the topological sorting, we check if there is a unique champion. If there is a unique champion, we return that team number, otherwise, we return -1.
- Build the directed graph from the given edges.
- Perform topological sorting.
- Check for a unique champion.
- Return the champion if unique, else return -1.
Time complexity: O(n + m) where n is the number of teams and m is the number of edges. Space complexity: O(n + m)
Solution Code
class Solution {
public int findChampion(int n, int[][] edges) {
List<Integer>[] graph = new ArrayList[n];
int[] indegree = new int[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int from = edge[0];
int to = edge[1];
graph[from].add(to);
indegree[to]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
int champion = -1;
int count = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
champion = node;
count++;
for (int neighbor : graph[node]) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
return count == 1 ? champion : -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2924 (Find Champion II)?
This page provides optimized solutions for LeetCode problem 2924 (Find Champion II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2924 (Find Champion II)?
The time complexity for LeetCode 2924 (Find Champion II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2924 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2924 in Java, C++, or Python.