Indented Staff Listing from Direct-Report Pairs
Trees & GraphsAuto-graded · 17 test casesLast 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:
- Take all people with no manager, sorted by ID ascending, and process them one after another in that order.
- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Find the heads. Scan the pairs once, collecting every ID into one set and every employee ID (anyone who has a manager) into another. The IDs in the first set but not the second are the heads of chains, and they get depth
0. - Build the child lists. Map each manager to the list of their direct reports. After all pairs are read, sort each list once so that the walk never has to sort.
- Walk the forest. Do a preorder depth-first traversal using an explicit stack. Seed the stack with the sorted heads in reverse order so the smallest head is popped first. When a person is popped, append
[person, depth]to the result, then push their sorted reports in reverse order withdepth + 1. The smallest report is then popped next, and its whole subtree is finished before the next sibling comes off the stack.
Why it is correct
The required ordering (a person, then the complete subtree of each direct report in ascending ID order) is exactly the definition of preorder. Because the heads and every report list are sorted, and the stack pops the smallest ID first, the output matches the specification. Each person has at most one manager and there are no cycles, so every ID is reached exactly once from exactly one head, and its depth is its distance from that head.
An explicit stack is used instead of recursion because a chain can be as deep as 10^5, which would exceed Python's default recursion limit.
Complexity
- Time: O(n log n), dominated by sorting the report lists and the head list. The traversal itself is O(n).
- Space: O(n) for the sets, the dictionary, the stack and the output.
Reference solution
from typing import List
def staff_listing_order(links: List[List[int]]) -> List[List[int]]:
reports = {}
everyone = set()
has_manager = set()
for employee, manager in links:
everyone.add(employee)
everyone.add(manager)
has_manager.add(employee)
reports.setdefault(manager, []).append(employee)
for group in reports.values():
group.sort()
heads = sorted(everyone - has_manager)
result = []
stack = [(head, 0) for head in reversed(heads)]
while stack:
person, depth = stack.pop()
result.append([person, depth])
group = reports.get(person, [])
for child in reversed(group):
stack.append((child, depth + 1))
return result