Traverse org chart level by level
Company: Microsoft
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of hierarchical data modeling and tree traversal, specifically breadth-first (level-order) traversal and reconstruction of a tree from manager–employee relationships.
Constraints
- 0 <= n <= 200000, where n is the number of relationships
- When n > 0, the relationships form a valid tree with exactly one root and no cycles
- Employees may appear before their manager in the input
- Aim for O(n) time and O(n) extra space
Examples
Input: ([('CEO', None), ('A', 'CEO'), ('B', 'CEO'), ('C', 'A')],)
Expected Output: [['CEO'], ['A', 'B'], ['C']]
Explanation: CEO is the root. A and B are on level 1, and C is under A on level 2.
Input: ([('C', 'A'), ('CEO', None), ('A', 'CEO'), ('B', 'CEO')],)
Expected Output: [['CEO'], ['A', 'B'], ['C']]
Explanation: C appears before A in the input, but it still belongs under A. The traversal is still level by level from the root.
Input: ([('CEO', None), ('B', 'CEO'), ('A', 'CEO'), ('D', 'A'), ('C', 'A')],)
Expected Output: [['CEO'], ['B', 'A'], ['D', 'C']]
Explanation: Sibling order follows input order: B appears before A under CEO, and D appears before C under A.
Input: ([(4, 2), (2, 1), (1, None), (3, 1), (5, 2)],)
Expected Output: [[1], [2, 3], [4, 5]]
Explanation: The root is 1. Its children are 2 then 3, and 2 has children 4 then 5.
Input: ([(42, None)],)
Expected Output: [[42]]
Explanation: A single employee is both the root and the only level.
Input: ([],)
Expected Output: []
Explanation: With no employees, there are no levels to return.
Hints
- First build a mapping from each manager to their direct reports, and remember which employee has `manager_id == None`.
- After finding the root, use a queue to process employees breadth-first and collect one level at a time.