KatInterview

Indented Staff Listing from Direct-Report Pairs

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphstreedfsforest

Last updated

Build a forest from (employee, manager) pairs and output each person with their depth in a sorted depth-first order, handling very deep chains iteratively.

Staff Directory Listing

A company stores its reporting structure as a list of pairs [employee_id, manager_id]. Each pair says that employee_id reports directly to manager_id. All IDs are positive integers.

An ID that never occurs as the first element (the employee) of any pair has no manager. Such a person is the head of their own reporting chain. There can be several heads, so the overall structure is a forest rather than a single tree.

Write a function that produces a flat listing of everyone, ready to be shown as an indented chart.

Task

Return a list with one entry [id, depth] for every distinct ID that appears anywhere in links, in the display order defined below.

Depth

  • A person with no manager has depth 0.
  • Every other person has depth equal to their direct manager's depth plus one.

Display order

The order is a depth-first preorder walk:

  1. Take all people with no manager, sorted by ID ascending, and process them one after another in that order.
  2. Processing a person means: output them first, then process each of their direct reports in ascending ID order. Each direct report's entire subtree is output before moving on to the next direct report.

Each person must appear exactly once in the result, and each entry is a two-element list [id, depth].

Constraints

  • 1 <= len(links) <= 10^5
  • IDs are positive integers up to 10^9.
  • Each ID appears as the employee in at most one pair (each person has at most one direct manager).
  • There are no cycles: following managers upward from any person always ends at someone with no manager.
  • A single chain may be as deep as the number of pairs, so a very deep hierarchy is possible.

Examples

Example 1

Input: staff_listing_order([[30, 10], [40, 10], [50, 30], [60, 30], [70, 50], [90, 80]])

Output: [[10, 0], [30, 1], [50, 2], [70, 3], [60, 2], [40, 1], [80, 0], [90, 1]]

Example 2

Input: staff_listing_order([[200, 100], [300, 200], [400, 200], [500, 300]])

Output: [[100, 0], [200, 1], [300, 2], [500, 3], [400, 2]]

Hints

Hint 1

Which IDs are heads of chains? Compare the set of all IDs with the set of IDs that appear as an employee.

Hint 2

Group employees under their manager in a dictionary, and sort each group once after all pairs have been read.

Hint 3

A preorder walk is a DFS. Chains can be about 100,000 levels deep, so use an explicit stack instead of recursion, pushing children in reverse sorted order so the smallest ID is popped first.