Traverse an Org Chart by Level
Company: Microsoft
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of tree and graph data structures, transforming flat employee-manager relations into a hierarchical org chart, level-order traversal, and reasoning about data integrity issues such as cycles, missing managers, or multiple roots.
Constraints
- 0 <= len(employees) <= 100000
- employee_id values must be unique for valid input
- Exactly one employee must have manager_id == None for valid input
- Every non-root manager_id must refer to an existing employee_id
- The reporting structure must form one connected acyclic tree
- Employee names may repeat
Examples
Input: ([[1, 'Mira CEO', None], [2, 'Nora VP', 1], [3, 'Omar VP', 1], [4, 'Priya Mgr', 2], [5, 'Quinn Mgr', 2], [6, 'Ravi Mgr', 3], [7, 'Sara IC', 4]],)
Expected Output: [['Mira CEO'], ['Nora VP', 'Omar VP'], ['Priya Mgr', 'Quinn Mgr', 'Ravi Mgr'], ['Sara IC']]
Explanation: The CEO is first, then both VPs, then all managers under those VPs, then the individual contributor under Priya.
Input: ([[2, 'VP Eng', 1], [4, 'Eng Mgr', 2], [1, 'CEO', None], [3, 'VP Sales', 1]],)
Expected Output: [['CEO'], ['VP Eng', 'VP Sales'], ['Eng Mgr']]
Explanation: The root does not need to appear first in the input. Children of CEO appear in their input order: VP Eng before VP Sales.
Input: ([[10, 'Solo CEO', None]],)
Expected Output: [['Solo CEO']]
Explanation: A single employee with no manager is a valid one-node org chart.
Input: ([[1, 'Alex', None], [2, 'Alex', 1], [3, 'Jordan', 1]],)
Expected Output: [['Alex'], ['Alex', 'Jordan']]
Explanation: Employee names may repeat because employee IDs are the unique identifiers.
Input: ([],)
Expected Output: []
Explanation: An empty employee list is invalid because there is no CEO/root.
Input: ([[1, 'CEO', None], [2, 'VP', 99]],)
Expected Output: []
Explanation: Employee 2 references manager_id 99, but no employee with ID 99 exists.
Input: ([[1, 'CEO One', None], [2, 'CEO Two', None]],)
Expected Output: []
Explanation: There are two roots, so the org chart is invalid.
Input: ([[1, 'CEO', None], [2, 'Alice', 3], [3, 'Bob', 2]],)
Expected Output: []
Explanation: Alice and Bob form a cycle disconnected from the CEO, so the reporting structure is invalid.
Hints
- Build a mapping from manager_id to the list of direct reports. This gives you the tree edges.
- After finding the root, use BFS with a queue to collect employees level by level. Track visited IDs to detect cycles or unreachable employees.