You are given a list of edges in a directed graph. Each edge is a pair [a, b] meaning there is a directed edge from node a to node b, so a is a parent of b.
Find all nodes that have exactly zero parents and all nodes that have exactly one parent. Return a list of two lists: the first holds the nodes with zero parents and the second holds the nodes with exactly one parent. Both lists are sorted in ascending order.
Function Signature
def find_nodes(edges: list[list[int]]) -> list[list[int]]:
Rules
-
The nodes of the graph are exactly the labels that appear in at least one edge, as a parent or as a child.
-
No edge
[a, b]
appears more than once, so a node's number of parents is the number of edges that end at it.
-
The graph may contain cycles, and a node may have any number of parents. Nodes with two or more parents appear in neither list.
-
Return
[zero_parents, one_parent]
with each list sorted ascending. Either list may be empty.
Constraints
-
1 <= len(edges) <= 10^4
-
Each edge is a pair of two distinct non-negative integers.
-
Node values are non-negative integers.
Examples
Input: edges = [[1, 4], [1, 5], [2, 5], [2, 6], [3, 6]]
Output: [[1, 2, 3], [4]]
Nodes 1, 2 and 3 never appear as a child, so they have zero parents. Node 4 has one parent (1), while nodes 5 and 6 have two parents each and are left out.
Input: edges = [[1, 2], [1, 3], [2, 6], [6, 7]]
Output: [[1], [2, 3, 6, 7]]
The graph is the path 1, 2, 6, 7 plus the edge from 1 to 3. Node 1 has no parent and every other node has exactly one.
Input: edges = [[0, 1], [1, 2], [2, 0], [0, 2]]
Output: [[], [0, 1]]
Every node lies on the cycle 0, 1, 2, so none has zero parents. Node 0 has one parent (2), node 1 has one parent (0), and node 2 has two parents (1 and 0).