Stop Listing and Indented Reporting Tree from Raw Inputs
Trees & GraphsAuto-graded · 15 test casesLast updated
Parse a JSON string into formatted stop lines and turn employee rows into a sorted, indented reporting-tree outline using an adjacency list and iterative DFS.
Write a function that handles two small, independent jobs and returns both results in one dictionary.
Part A: Stop lines
payload_text is a string containing valid JSON. It is an object that may contain a key "stops" holding a list of objects. Each stop object may have the keys "id", "name" and "description".
For every stop, in the order given, build the string
<name> - <description>
- If
"name"is absent, use the empty string in its place. - If
"description"is absent, use the empty string in its place. An empty description stays empty. The separator-(space, hyphen, space) is always present, so the line still ends with" - ". - If the
"stops"key is absent, the result for this part is an empty list.
Part B: Reporting-tree outline
staff_rows is a list of rows. Each row has exactly four strings:
[employee_name, title, department, manager_name]
manager_nameis the empty string for a top-level leader.- Every non-empty
manager_nameis theemployee_nameof some row in the list. - Employee names are unique, and the reporting relation has no cycles.
- There may be zero, one, or several top-level leaders.
Produce a list of strings, one per employee, that lists the organisation as an outline:
- A top-level leader is at depth 0, their direct reports at depth 1, and so on.
- Each line is the employee name preceded by
2 * depthspace characters. - Every employee appears directly after the lines of the previous sibling's whole subtree, so each manager is followed immediately by their own subtree (pre-order).
- Sibling groups are sorted in ascending lexicographic (plain string comparison) order by
employee_name. This applies to the top-level leaders as well as to each manager's direct reports. - The row order in the input is arbitrary and carries no meaning.
Return value
Return a dictionary with exactly two keys:
{"stops": <list of strings from Part A>, "org_chart": <list of strings from Part B>}
The input can be large, so a solution that rescans all rows for every manager is too slow. Aim for roughly O(n log n) time.
Constraints
payload_textis always valid JSON and its top level is an object.- The number of stops is at most
10^5. 0 <= len(staff_rows) <= 2 * 10^5.- Reporting chains can be very deep (up to the number of employees), so avoid relying on deep recursion.
- Names contain no commas or newlines.
Examples
Example 1
Input: stops_and_org_outline('{"stops":[{"id":"123","name":"South Station","description":"Commuter rail hub"},{"id":"456","name":"Park Street","description":"Red/Green lines"}]}', [['Alice', 'CEO', 'Executive', ''], ['Bob', 'CFO', 'Finance', 'Alice'], ['Carol', 'Analyst', 'Finance', 'Bob'], ['Dave', 'Intern', 'Finance', 'Carol'], ['Eve', 'COO', 'Operations', 'Alice'], ['Frank', 'CTO', 'Engineering', 'Alice']])
Output: {'stops': ['South Station - Commuter rail hub', 'Park Street - Red/Green lines'], 'org_chart': ['Alice', ' Bob', ' Carol', ' Dave', ' Eve', ' Frank']}
Example 2
Input: stops_and_org_outline('{"stops":[{"id":"1","name":"Central","description":""},{"id":"2","name":"Mystic"}]}', [['Zoe', 'CEO', 'Exec', ''], ['Amy', 'Engineer', 'Tech', 'Zoe'], ['Ben', 'Engineer', 'Tech', 'Zoe'], ['Ann', 'Intern', 'Tech', 'Amy']])
Output: {'stops': ['Central - ', 'Mystic - '], 'org_chart': ['Zoe', ' Amy', ' Ann', ' Ben']}
Example 3
Input: stops_and_org_outline('{"stops":[]}', [])
Output: {'stops': [], 'org_chart': []}
Hints
Hint 1
Treat the two parts separately: json.loads plus dict.get with an empty-string default handles the stops, and the rest is a tree problem.
Hint 2
Build a map from each manager name to the list of their direct reports in one pass over the rows, then sort every list. Employees whose manager is the empty string are the roots.
Hint 3
Use pre-order DFS with an explicit stack to avoid recursion limits. Push children in reverse sorted order so they pop in ascending order, and store the depth with each stack entry to build the indentation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part A (stop lines). Decode the JSON string, then walk the "stops" list (empty if the key is missing). For each stop, read name and description with dict.get(key, "") and format them as "<name> - <description>". Order is preserved.
Part B (outline). The employees form a forest, which we store as an adjacency list.
- One pass over the rows: if the manager field is empty, add the employee to
roots. Otherwise append the employee toreports_of[manager]. - Sort
rootsand every list of reports. - Run an iterative pre-order DFS. The stack holds
(name, depth)pairs, seeded with the roots in reverse sorted order. Pop a node, emit" " * depth + name, then push its reports in reverse sorted order withdepth + 1.
Why it is correct
- Each employee has at most one manager and there are no cycles, so every employee is reachable from exactly one root and is visited exactly once.
- Pre-order emits a manager before any of their descendants, and a whole subtree is emitted contiguously before the next sibling.
- Pushing children in reverse sorted order makes the stack pop them in ascending order, so siblings come out lexicographically sorted.
- The depth carried on the stack equals the distance from the root, which gives the correct indentation.
- An explicit stack avoids recursion-limit failures on very deep chains.
Complexity
- Part A:
O(s)forsstops (plus JSON parsing time). - Part B: building is
O(n). Sorting all sibling groups costs at mostO(n log n). The DFS isO(n). - Overall time is
O(n log n)and extra space isO(n).
Reference solution
import json
from typing import Dict, List
def stops_and_org_outline(payload_text: str, staff_rows: List[List[str]]) -> Dict[str, List[str]]:
data = json.loads(payload_text)
stop_lines: List[str] = []
for stop in data.get("stops", []):
stop_lines.append(f"{stop.get('name', '')} - {stop.get('description', '')}")
reports_of: Dict[str, List[str]] = {}
roots: List[str] = []
for name, _title, _department, manager in staff_rows:
if manager == "":
roots.append(name)
else:
reports_of.setdefault(manager, []).append(name)
for reports in reports_of.values():
reports.sort()
roots.sort()
outline: List[str] = []
stack = [(root, 0) for root in reversed(roots)]
while stack:
name, depth = stack.pop()
outline.append(" " * depth + name)
for report in reversed(reports_of.get(name, [])):
stack.append((report, depth + 1))
return {"stops": stop_lines, "org_chart": outline}