Loading...
You are given an integer n and a directed graph with n nodes labeled 0 to n - 1, described by a 0-indexed list edges, where edges[i] = [u, v] is a directed edge from node u to node v.
Find the node that satisfies both of the following:
Return that node's index if exactly one node satisfies both conditions. Otherwise return -1.
Note that edges may contain duplicate edges, and a graph with a single node and no edges has a valid answer: node 0 vacuously reaches every other node.
Input: n = 4, edges = [[0,1],[1,2],[2,3]]
Output: 0
Explanation: Node 0 has no incoming edges, and following the chain
0 -> 1 -> 2 -> 3 reaches every other node.
Input: n = 4, edges = [[0,1],[2,1],[1,3]]
Output: -1
Explanation: Both node 0 and node 2 have no incoming edges, so there is no
single node satisfying both conditions.
Input: n = 5, edges = [[2,0],[2,1],[2,3],[3,4]]
Output: 2
Explanation: Node 2 is the only node with no incoming edges. It reaches 0, 1,
and 3 directly, and reaches 4 through 3.
n ≤105edges.length ≤105edges[i] =[u,v] with 0≤u,v<n and u=vedges may contain duplicate edges.Click "Run" to test with sample cases or "Submit" to run all tests.