Find Champion Ii
Algorithm/Graph
Intuition
In a directed graph, a "champion" can be identified as a node that does not have any incoming edges. The task is to determine if there exists exactly one such node. If there is no such node or there are multiple such nodes, the result should be -1.
This can be solved efficiently by leveraging an array to track which nodes have incoming edges.
Approach
Below is the step-by-step breakdown of the approach:
-
Initialize Tracking Array:
- Use an array isWeak of size n to record whether each node has incoming edges. Each entry starts as false (no incoming edges).
-
Process the Edges:
- For every directed edge
[u, v]
, markisWeak[v] = true
since node v has at least one incoming edge.
- For every directed edge
-
Find the Candidate Champion:
- Iterate through all nodes to find the one that has no incoming edges.
- If more than one node meets this condition, return -1.
-
Return the Result:
- If exactly one node without incoming edges is found, return its index.
- Otherwise, return -1.
Complexity
- Time Complexity: , processing all edges takes , where m is the number of edges. Iterating through all nodes to check their status takes .
- Space Complexity: , the isWeak array requires space.