KatInterview

Group Staff Names by Reporting Depth

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphsbfstreehash-map

Last 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 or None): the id of the person's direct manager, or None for 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 None in 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 id values 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).