KatInterview

Group Hierarchy Members by Depth Level

Trees & GraphsAuto-graded · 18 test cases
EasyAuto-gradedTrees & Graphstrees-graphsbfshash-map

Last updated

Construct an adjacency graph from reporting links and perform a level-order traversal to group node IDs by depth.

Given a collection of structural links within an organization, organize the members into lists corresponding to their depth level from the top-level leader (the node without a superior).

Each input element is represented as a pair [member_id, superior_id].

  • A top-level leader (root) has superior_id set to None (or null). There is guaranteed to be exactly one root node.
  • Every other member reports directly to exactly one superior.

Return a list of lists, where the outer list represents levels starting at depth 0 (containing only the root), depth 1 (the root's direct reports), depth 2 (reports of depth 1 members), and so forth.

Members in the same output level should preserve the relative order in which their reporting relationships appeared in the input list.

Constraints

  • n (total number of members) is between 1 and 10,000.
  • Each member ID is a unique integer.
  • Exactly one pair in the input has a superior_id of None.
  • The reporting hierarchy forms a single valid tree structure with no cycles.

Examples

Example 1

Input: get_org_levels([[1, None], [2, 1], [3, 1], [4, 2]])

Output: [[1], [2, 3], [4]]

Example 2

Input: get_org_levels([[10, None], [20, 10], [30, 10], [40, 20], [50, 30]])

Output: [[10], [20, 30], [40, 50]]

Hints

Hint 1

The provided pairs describe child-to-parent relationships. You need to reverse these to traverse downward from parent to children.

Hint 2

Identify the root node where superior_id is None to start your traversal.

Hint 3

Use a level-by-level Breadth-First Search (BFS) to process each level as a list of IDs before moving to their reports.