Group Staff Names by Reporting Depth
Trees & GraphsAuto-graded · 15 test casesLast updated
Turn flat employee-manager records into a list of name groups by depth from the top manager, using a level-by-level breadth-first traversal.
Reporting Levels
A company stores its staff as a flat list of records. Each record is a dictionary with three keys:
id(int): a unique identifier for the person.name(str): the person's name.manager_id(int orNone): theidof the person's direct manager, orNonefor the top-level person.
The person whose manager_id is None is the top of the hierarchy and sits at depth 0. Their direct reports sit at depth 1, those people's direct reports at depth 2, and so on.
Write a function that groups the names by depth. Return a list of lists: the first inner list holds the names at depth 0, the second holds the names at depth 1, and so on.
Ordering rule
Within one depth, names must appear in the order produced by a level-order (breadth-first) traversal, where every person's direct reports are visited in the order their records appear in the input list. Concretely, people at a depth are grouped by their manager's position in the previous depth's list, and people who share a manager are ordered by input position.
Edge cases
- If the input list is empty, return an empty list.
- A hierarchy with a single person returns a list containing one list with that person's name.
- Exactly one person has a manager of
Nonein valid inputs, and the structure is a proper tree with no cycles. - A record that cannot be reached from the top person is not included in the result.
Constraints
- The number of records is at most 10,000.
- All
idvalues are unique. - The structure is guaranteed to be a valid tree (no cycles).
- Names are not guaranteed to be unique.
Examples
Example 1
Input: group_names_by_depth([{'id': 1, 'name': 'Alice', 'manager_id': None}, {'id': 2, 'name': 'Bob', 'manager_id': 1}, {'id': 3, 'name': 'Charlie', 'manager_id': 1}, {'id': 4, 'name': 'David', 'manager_id': 2}])
Output: [['Alice'], ['Bob', 'Charlie'], ['David']]
Example 2
Input: group_names_by_depth([{'id': 10, 'name': 'CEO', 'manager_id': None}])
Output: [['CEO']]
Example 3
Input: group_names_by_depth([])
Output: []
Hints
Hint 1
Flat records point from child to parent, but you need to walk from parent to children. Build a mapping from each manager id to the list of their direct reports, preserving input order.
Hint 2
Grouping nodes by distance from a starting node is exactly what breadth-first search does. Start from the person whose manager_id is None.
Hint 3
To keep levels separate, record the queue length at the start of each round and process exactly that many people, adding their reports to the queue for the next round. Use a deque so removals from the front are O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The records point upward (person to manager), but the answer is organized by distance from the top. Grouping nodes by distance from a start node is what breadth-first search does, so the solution has two phases.
- Build a children map. Walk the records once. For each record with a manager, append it to that manager's list of direct reports, which keeps input order. The record with
manager_idofNoneis the top person. - Traverse level by level. Put the top person in a queue. In each round, the queue holds exactly one depth. Take its current length, remove that many people, record their names as one inner list, and push their direct reports onto the queue. Those reports form the next depth.
If there is no top person (empty input), return an empty list.
Why it is correct
- Levels stay separate: At the start of the first round the queue holds only the depth-0 person. In each round we remove only the people of the current depth and add only their direct reports, who are exactly the people of the next depth. By induction, every round processes one complete depth and nothing else.
- Everyone appears once: In a tree each non-top person has one manager, so they are enqueued exactly once, when that manager is processed.
- Ordering: The queue is first-in-first-out and each manager's reports are stored in input order, so people at a depth are grouped by their manager's order in the previous depth, with siblings in input order. This is the ordering the problem defines.
- Unreachable records: Anyone not connected to the top person is never enqueued and is omitted.
Complexity
- Time: O(n). Building the map is one pass, and each person is enqueued and dequeued once.
- Space: O(n) for the map and the output. The queue never holds more than one level.
An iterative traversal also avoids recursion-depth problems on a chain of 10,000 levels.
Reference solution
from collections import defaultdict, deque
from typing import Dict, List
def group_names_by_depth(records: List[Dict]) -> List[List[str]]:
reports = defaultdict(list)
top = None
for rec in records:
mgr = rec["manager_id"]
if mgr is None:
top = rec
else:
reports[mgr].append(rec)
if top is None:
return []
result = []
queue = deque([top])
while queue:
level = []
for _ in range(len(queue)):
person = queue.popleft()
level.append(person["name"])
queue.extend(reports[person["id"]])
result.append(level)
return result