Nodes With Zero or One Parent
Problem statement
Each row of pairs is [parent,child] and describes one directed parent-child relationship. Return all represented nodes with no direct parents and all represented nodes with exactly one distinct direct parent. Count direct parents, rather than all ancestors.
For this exercise, assume the relationships form a directed acyclic graph that permits multiple parents. Repeated copies of the same pair count as one relationship.
Return exactly two rows: [roots,nodesWithOneParent]. For this exercise, assume each row is sorted by increasing numeric ID; only nodes appearing as a parent or child are represented, and empty input returns [[],[]].
Function
findNodesWithZeroOrOneParent(pairs: int[][]) → int[][]Examples
Example 1
pairs = [[1,3],[2,3],[4,2],[4,7]]return = [[1,4],[2,7]]The original report's sample yields roots 1 and 4 and one-parent nodes 2 and 7, returned in numeric order.
Example 2
pairs = [[4,1],[4,2],[2,3]]return = [[4],[1,2,3]]Only direct parents are counted. Node 4 is a root; the remaining nodes each have one direct parent.
Constraints
- For this exercise, assume
0 <= pairs.length <= 1000. - Every row contains exactly two positive integer IDs, each at most
10^9. - The directed relationships contain no cycles; duplicate pairs may appear.