Snowflake questions

Reporting Forest

SnowflakeOnsiteMedium

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.

Part 1: Preorder rows

Given the org chart as pairs, return the forest as preorder rows [id, depth].

Roots have depth 0 and every other person's depth is their manager's depth plus 1. Visit the trees in ascending order of root id and, inside a tree, visit each person's direct reports in ascending order of id. Every person appears exactly once.

  1. Example 1
    pairs
    [[2,1],[3,1],[4,2],[5,6]]
    Output
    [[1,0],[2,1],[4,2],[3,1],[6,0],[5,1]]

    Why: 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.

  2. Example 2
    pairs
    [[9,7],[7,3],[4,3]]
    Output
    [[3,0],[4,1],[7,1],[9,2]]

    Why: 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.

Constraints

  • 1 <= len(pairs) <= 10^5
  • 1 <= employee, manager <= 10^9
  • employee != manager
  • each employee appears in at most one pair
  • a chain of managers can be as long as len(pairs)
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Reporting Forest: Snowflake interview question | LoopCoach