Reporting Forest
Asked at Snowflake
Reported by the problem's creator, not verified
A company's org chart is given as pairs [employee, manager]. Every person has at most one manager, nobody reports to themselves, and there are no cycles. People who never appear as an employee are top-level managers, and each is the root of a tree: together the trees form a forest.
Examples
Example 1
Input: pairs =
[[2,1],[3,1],[4,2],[5,6]]Output:
[[1,0],[2,1],[4,2],[3,1],[6,0],[5,1]]Explanation: Managers that are never an employee are roots: 1 and 6. Tree 1 has reports 2 and 3 (ascending), and 2 has report 4, so the preorder is 1, 2, 4, 3; then the tree of 6 gives 6, 5. Depths count the managers above each person.
Example 2
Input: pairs =
[[9,7],[7,3],[4,3]]Output:
[[3,0],[4,1],[7,1],[9,2]]Explanation: Root 3 has reports 4 and 7, and 7 has report 9, so the preorder is 3, 4, 7, 9 with depths 0, 1, 1, 2.