Print a Reporting Hierarchy and List Two-Level-Down Pairs
Trees & GraphsModel answerLast updated
Turn manager rows into a tree, infer the root, print it with depth-based dot indentation, or list every (manager, employee) pair exactly two levels apart.
You are given the reporting structure of a company as a list of rows. Each row has the form [manager, report1, report2, ...]. The reports are listed in the order they should be displayed. Implement:
org_chart(relations: string[][], mode: int) -> string[]
Mode 0 (print the hierarchy). Return one string per employee in preorder: an employee, then each of its subtrees in the stored order. Each line is the employee name preceded by four . characters for every level of depth. The root is at depth 0 and has no prefix.
Mode 1 (two-level-down pairs). Return strings of the form manager,employee (one comma, no spaces) for every pair where employee is exactly two edges below manager. Not one edge, and not three or more.
- Process managers in tree preorder.
- For one manager, go through its direct reports in order, and for each of them go through that report's own reports in order.
Rules and constraints
- Names are nonempty ASCII strings made of letters, digits, and underscores.
- A manager is the head of at most one row, and no row lists the same report twice.
- The rows describe a single valid rooted tree of at most 2,000 employees: no cycles, exactly one parent for every non-root employee, exactly one root. The root is not given, so you must infer it.
- A row with one element (such as
["B"]) is an employee with no reports. Employees who only ever appear as reports are leaves and need no row of their own. - An empty
relationslist means an empty chart, so return[]in both modes. - Keep the input order of reports. Do not sort.
Examples
relations = [["A","B","C"],["B","E"],["C","D"]]
mode = 0
result = ["A","....B","........E","....C","........D"]
relations = [["A","B","C"],["B","E"],["C","D"]]
mode = 1
result = ["A,E","A,D"]
What to deliver
Write the function, then discuss the time and space cost of building the tree, printing it, and listing the pairs, including the size of the returned strings. Describe how you would test a single-root chart, a chain, and a branching tree.
Hints
Hint 1
The root is the one employee who is the head of a row but never appears in anyone's report list. Collect all report names into a set while you build the manager-to-reports map.
Hint 2
Printing needs absolute depth from the root, so carry a depth counter in the traversal. Pair listing only needs relative distance: from each manager, look at its reports, then at their reports. The manager's own depth is irrelevant.
Hint 3
A chain of 2,000 employees would overflow a naive recursive DFS in many languages, so use an explicit stack and push children in reverse order to keep input order. Also notice that printing a chain produces about 2n² characters, which is a property of the output itself.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task splits into three small steps.
- Build the structure. Walk the rows once. Store
reports[manager]as the ordered list of that row's reports, and put every report name into a setseen_as_report. - Find the root. It is the row head that is not in
seen_as_report. Because the input is guaranteed to be one valid tree, exactly one such head exists. A lone row like[["A"]]also works, since A heads a row and nobody lists it. Ifrelationsis empty, return[]immediately. - Traverse in preorder and answer the mode.
- Mode 0: for each visited node emit
"." * (4 * depth) + name. - Mode 1: for each manager in the preorder, loop over
reports.get(manager, []), and for each report loop overreports.get(report, []), emittingmanager,grandreport.
- Mode 0: for each visited node emit
Use .get(x, []) everywhere so that leaves without their own row need no special case.
Depth versus distance
This is the most common source of bugs. Printing depends on the absolute depth from the root. A two-level-down pair depends only on the relative distance from the current manager. Typical mistakes are producing pairs only for the root, or including every deeper descendant instead of exactly two edges.
Why an explicit stack
A chain of 2,000 employees means 2,000 nested levels. That exceeds Python's default recursion limit of about 1,000. An iterative preorder avoids the issue:
- Pop
(node, depth), record it. - Push its reports in reverse order with
depth + 1.
The first report is then popped next, and its entire subtree is finished before the second report is touched. That gives preorder with the original child order preserved.
Why the pair order is right
- Managers come out in preorder, as required.
- Within one manager, the nested loops group pairs by direct report (in stored order), then by that report's reports (in stored order). In the example,
A,E(through B) comes beforeA,D(through C). - Every non-root employee has one parent, so it has at most one grandparent and appears as the second element of at most one pair. No duplicates are possible.
Code
from typing import List, Dict
def org_chart(relations: List[List[str]], mode: int) -> List[str]:
reports: Dict[str, List[str]] = {}
seen_as_report = set()
for row in relations:
if not row:
continue
boss, *team = row
reports.setdefault(boss, []).extend(team)
seen_as_report.update(team)
if not reports:
return []
root = next(b for b in reports if b not in seen_as_report)
order = [] # (name, depth) in preorder
stack = [(root, 0)]
while stack:
name, depth = stack.pop()
order.append((name, depth))
for r in reversed(reports.get(name, [])):
stack.append((r, depth + 1))
if mode == 0:
return ["." * (4 * d) + name for name, d in order]
pairs = []
for boss, _ in order:
for mid in reports.get(boss, []):
for low in reports.get(mid, []):
pairs.append(f"{boss},{low}")
return pairs
Complexity
Let n be the number of employees and L the total length of all names.
| Step | Time | Extra space |
|---|---|---|
| Build map and set | O(n + L) | O(n) |
| Find root | O(n) | O(1) |
| Preorder traversal | O(n) | O(n) |
| Mode 0 output | O(n + L + total dots) | size of the output |
| Mode 1 output | O(n + L) | O(L) |
The nested loops in mode 1 are not cubic. Each employee is reached as a "grandreport" at most once, through its unique grandparent, so total inner work is O(n). There are at most n - 2 pairs, and each string is two names plus a comma.
Mode 0 output size is the subtle part. Each line has 4 * depth dots. For a bushy tree the depths are small and the output is close to O(L). For a chain, depths run from 0 to n - 1, so the dots total 4 * n(n-1)/2 = 2n(n-1), about 8 million characters for n = 2,000. Rendering is therefore Θ(n² + L) in the worst case, and no algorithm can do better because the required output itself is that large. Saying everything is linear is a mistake here.
Edge cases
[]returns[]in both modes.[["A"]]: mode 0 gives["A"], mode 1 gives[].- A root with only leaf children gives no pairs.
- A one-element row for a non-root (for example
["B"]when B is also someone's report) is a leaf. - Rows can come in any order, including the root's row last.
- Never sort, since input order is part of the answer.
Tests to describe
- Single root.
[["A"]]gives["A"]in mode 0 and[]in mode 1. Also the empty list in both modes. - Chain.
[["A","B"],["B","C"],["C","D"]]- Mode 0:
["A","....B","........C","............D"] - Mode 1:
["A,C","B,D"]. This confirms pairs start at every manager and thatA,D(three edges) is excluded. - A 2,000-node chain checks there is no recursion failure and shows the quadratic output.
- Mode 0:
- Branching tree. The statement example gives the expected outputs above. Add:
- The same tree with
["A","C","B"], to catch accidental sorting. [["R","X","Y"],["X","P","Q"],["Y","S"],["P","T"]], whose mode 1 answer is["R,P","R,Q","R,S","X,T"].
- The same tree with
- Row order.
[["B","E"],["C","D"],["A","B","C"]]must still find A as the root.
Common mistakes
- Choosing the root as the first row's head instead of the head that is never a report.
- Counting all descendants below one level rather than exactly two edges.
- Recursing on deep chains.
- Reversing or sorting the children.
- Claiming O(n) total time while ignoring the size of the printed output.