Format Stop JSON and Indented Org Tree
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement parse_api_json_and_org_chart(response_body: str, rows: List[List[str]]) -> Dict[str, List[str]], which combines two data-formatting subtasks and returns both line lists in a single dictionary:
{
"stops": [...], # formatted station lines from Part 1
"org_chart": [...], # indented hierarchy lines from Part 2
}
Part 1 — Station Feed Formatting ("stops")
A transit service exposes an HTTP GET endpoint whose UTF-8 payload is passed to your function as response_body. The JSON document is an object with a "stops" array:
{
"stops": [
{"id": "S10", "name": "Union Depot", "description": "Regional rail terminal"},
{"id": "S25", "name": "Harbor Pier", "description": "Ferry transfer point"}
]
}
For each station object in "stops" (keeping their original array order):
- Read
"name"and"description". - Treat an omitted
"description", a JSONnullvalue, or""as an empty string""(and treat a missing ornull"stops"key as an empty list). Ignore any unrelated fields on a station object. - Produce a string formatted as
"<name> - <description>", always retaining the" - "delimiter even when"description"resolves to""(for instance,"North Gate - ").
(You may also structure a separate helper that fetches a live URL over HTTP GET and delegates the decoded body to your JSON parser.)
Part 2 — Indented Reporting Hierarchy ("org_chart")
rows contains parsed 4-column personnel records in arbitrary row order:
[employee_name, title, department, manager_name]
- Leading or trailing whitespace around names should be ignored (
strip()), and a 3-column record is treated as havingmanager_name == "". - Top-level executives have
manager_name == "". Every other person reports to exactly one manager. - Render the hierarchy in pre-order so every manager is emitted immediately ahead of their entire reporting subtree.
- Prefix each
employee_namewith" " * depth(two spaces per reporting level:0spaces for top-level executives,2spaces for their direct reports,4spaces at depth2, and so on). - Sort top-level executives—and every manager's direct report list—in standard lexicographic (
ASCII/Unicode code-point) order byemployee_name.
Examples
Example 1
Input:
response_body = '{"stops":[{"id":"S10","name":"Union Depot","description":"Regional rail terminal"},{"id":"S25","name":"Harbor Pier","description":"Ferry transfer point"}]}'
rows = [
["Gabe", "VP Finance", "Finance", "Clara"],
["Maya", "VP Platform", "Engineering", "Clara"],
["Clara", "CEO", "Leadership", ""],
["Jude", "Associate", "Finance", "Iris"],
["Liam", "VP Ops", "Operations", "Clara"],
["Iris", "Controller", "Finance", "Gabe"]
]
Output:
{
"stops": [
"Union Depot - Regional rail terminal",
"Harbor Pier - Ferry transfer point"
],
"org_chart": [
"Clara",
" Gabe",
" Iris",
" Jude",
" Liam",
" Maya"
]
}
Walk-through: Both station entries carry text descriptions, so they format in input order. In rows, "Clara" has no manager (depth = 0). Her direct reports sort to ["Gabe", "Liam", "Maya"]; "Gabe"'s entire chain ("Iris" -> "Jude") is emitted at depths 2 and 3 before moving on to "Liam" and "Maya".
Example 2
Input:
response_body = '{"stops":[{"id":"B1","name":"Civic Plaza","description":""},{"id":"B2","name":"North Gate"},{"id":"B3","name":"West Loop","description":null}]}'
rows = [
["Nora", "Founder", "Exec", ""],
["Theo", "Lead", "Product", "Nora"],
["Dina", "Lead", "Infra", "Nora"],
["Eli", "Intern", "Infra", "Dina"]
]
Output:
{
"stops": [
"Civic Plaza - ",
"North Gate - ",
"West Loop - "
],
"org_chart": [
"Nora",
" Dina",
" Eli",
" Theo"
]
}
Walk-through: Empty, omitted, and null descriptions all normalize to "" after " - ". Under "Nora", "Dina" precedes "Theo" alphabetically, and "Eli" appears directly beneath "Dina" with four leading spaces.
Example 3
Input:
response_body = '{"stops":[]}'
rows = [
["Vera", "Co-CEO", "Exec", ""],
["Omar", "Co-CEO", "Exec", ""],
["Kira", "Analyst", "Ops", "Omar"]
]
Output:
{
"stops": [],
"org_chart": [
"Omar",
" Kira",
"Vera"
]
}
Walk-through: An empty "stops" array yields []. Two executives have manager_name == "", so "Omar" and his subtree print first, followed by "Vera" at depth 0.
Constraints
response_bodyis valid UTF-8 JSON representing a top-level object.0 <= len(rows) <= 10^5; employee names are unique withinrows.- The manager relationship forms a cycle-free forest, and every non-empty
manager_namematches someemployee_nameinrows. - Reporting chains may be thousands of levels deep, and repeated
O(n^2)scans overrowsare too slow; aim forO(n log n)time andO(n)space.
Step-by-step walkthrough
Understand both subtasks and the return shape
parse_api_json_and_org_chart(response_body, rows)bundles two independent formatting subtasks into one dictionary so an offline test harness can verify both without network access:{ "stops": ["Union Depot - Regional rail terminal", "Harbor Pier - Ferry transfer point"], "org_chart": ["Clara", " Gabe", " Iris", " Jude", " Liam", " Maya"] }- Part 1 (Station JSON): Decode
response_bodyand build one"<name> - <description>"string per station in array order. Look at Example 2: wheneverdescriptionis"",null, or omitted, the" - "delimiter stays intact ("North Gate - "). - Part 2 (Reporting hierarchy): Each record in
rowsis[employee_name, title, department, manager_name]. Top-level executives havemanager_name == "". Emit every manager ahead of their subtree, indent by 2 spaces per level, and sort siblings lexicographically byemployee_name.
Keeping
fetch_stops(url)separate fromformat_stops(response_body)is good engineering practice: network I/O lives at the boundary, while string parsing remains pure and deterministic.- Part 1 (Station JSON): Decode
Part 1: Decode station JSON and normalize missing descriptions
json.loads(response_body)converts the JSON string into Python dictionaries and lists. The subtle edge case is"description", which can arrive in three "blank" states:"description": ""->stop.get("description")returns"""description": null->stop.get("description")returnsNone- Key omitted entirely ->
stop.get("description")returnsNone
Formatting
stop.get("description")directly in an f-string would turn cases 2 and 3 into"North Gate - None". A smalltext_fieldhelper normalizesNoneto""in one place.import json import urllib.request # ---------- Task 1: Transit stops from API JSON ---------- def text_field(stop: Dict[str, Any], key: str) -> str: """Extract stop[key] as a string, converting missing keys or JSON null into ''.""" value = stop.get(key) # Both a missing key and {"description": null} arrive as None in Python. if value is None: return "" return str(value) def format_stops(response_body: str) -> List[str]: """Parse API JSON text and format one '<name> - <description>' line per stop.""" payload = json.loads(response_body) # Guard against a missing or null "stops" list. stops = payload.get("stops") or [] lines: List[str] = [] for stop in stops: name = text_field(stop, "name") description = text_field(stop, "description") # Keep the " - " separator even when description is empty (e.g., "North Gate - "). lines.append(f"{name} - {description}") return lines def fetch_stops(url: str, timeout_seconds: float = 5.0) -> List[str]: """Perform the HTTP GET request with a timeout and format the returned stops.""" # Separated from format_stops so the offline judge can test JSON parsing without network I/O. with urllib.request.urlopen(url, timeout=timeout_seconds) as response: body = response.read().decode("utf-8") return format_stops(body)Part 2: Why rescanning rows per manager takes O(n²) time
Suppose we find
"Clara"at depth0and scan allnrecords to collect everyone reporting to"Clara". Next, for"Gabe", we scan allnrecords a second time; then for"Iris", we scan allnrecords again.Repeating a full
O(n)table scan for each of thenemployees costsO(n²)work (100,000employees would trigger10,000,000,000comparisons). We are re-reading the entire input just to answer "who reports directly toX?"Group direct reports in a single O(n) pass
Instead, read
rowsonce and bucket each employee under theirmanager_namein a dictionarydirect_reports(an adjacency list — a lookup table mapping every parent node to its list of direct children):Unsorted input rows: One O(n) pass + per-list sort: [Gabe, ..., Clara] leaders = ["Clara"] [Maya, ..., Clara] direct_reports = { [Clara, ..., ""] ---> "Clara": ["Gabe", "Liam", "Maya"], [Jude, ..., Iris] "Gabe": ["Iris"], [Liam, ..., Clara] "Iris": ["Jude"], [Iris, ..., Gabe] }Input order does not matter: even though
"Jude"appears before"Iris", we simply recorddirect_reports["Iris"] = ["Jude"]and connect"Iris"under"Gabe"when her row arrives. Afterward, we sortleadersand sort each manager's list once. Since every employee sits in at most one list, the list lengths sum tonand sorting all of them takes at mostO(n log n)comparisons total.# ---------- Task 2: Org chart from CSV rows ---------- def build_reports(rows: List[List[str]]) -> Tuple[List[str], Dict[str, List[str]]]: """Group CSV rows into sorted top-level leaders and a manager -> sorted direct reports map.""" # leaders: sorted list of top-level employee names (rows where manager_name == "") leaders: List[str] = [] # direct_reports: maps manager_name -> sorted list of direct report employee names direct_reports: Dict[str, List[str]] = {} # Phase 1: Scan all n rows once in O(n) time to group every employee under their manager. for row in rows: employee_name = row[0].strip() manager_name = row[3].strip() if len(row) > 3 else "" if manager_name == "": leaders.append(employee_name) else: if manager_name not in direct_reports: direct_reports[manager_name] = [] direct_reports[manager_name].append(employee_name) # Phase 2: Sort leaders and each manager's direct report list lexicographically. leaders.sort() for report_list in direct_reports.values(): report_list.sort() return leaders, direct_reportsEmit indented lines with iterative pre-order DFS
In Example 1,
"Gabe","Iris", and"Jude"all appear before"Liam", even though"Liam"sits at depth1and"Jude"sits at depth3. That visit order is pre-order depth-first search (DFS): emit a manager first, then emit their entire reporting subtree before advancing to the manager's next sibling.A recursive function can hit Python's default
~1,000-frame call-stack limit on a deep3,000-level reporting chain and raiseRecursionError. Using an explicit(employee_name, depth)stack avoids call-stack limits completely:- Pop
(employee_name, depth)and append" " * depth + employee_name. - Push
employee_name's direct reports in reverse sorted order (reversed(children)): because a stack is last-in, first-out, pushing"Maya","Liam","Gabe"leaves"Gabe"on top so"Gabe"is popped next.
def org_chart_lines(rows: List[List[str]]) -> List[str]: """Build the indented org chart using iterative pre-order DFS.""" leaders, direct_reports = build_reports(rows) lines: List[str] = [] # Phase 3: Iterative pre-order DFS using an explicit LIFO stack of (employee_name, depth) # so deep chains (e.g., 3,000 levels) never hit Python's ~1,000-call recursion limit. stack: List[Tuple[str, int]] = [] for leader in reversed(leaders): stack.append((leader, 0)) while stack: employee_name, depth = stack.pop() indent = " " * depth lines.append(indent + employee_name) # Push direct reports in reverse order so the alphabetically first report sits on top # of the LIFO stack and gets popped next. children = direct_reports.get(employee_name, []) for report_name in reversed(children): stack.append((report_name, depth + 1)) return lines- Pop
Trace Example 1 step by step
For Example 1,
leaders = ["Clara"]anddirect_reports = {"Clara": ["Gabe", "Liam", "Maya"], "Gabe": ["Iris"], "Iris": ["Jude"]}. Watch the stack (top of stack on the right) acrossorg_chart_lines:Stack before pop (top on right) | Popped | Appended line ----------------------------------------+-------------+-------------- [("Clara", 0)] | ("Clara",0) | "Clara" [("Maya", 1), ("Liam", 1), ("Gabe", 1)] | ("Gabe", 1) | " Gabe" [("Maya", 1), ("Liam", 1), ("Iris", 2)] | ("Iris", 2) | " Iris" [("Maya", 1), ("Liam", 1), ("Jude", 3)] | ("Jude", 3) | " Jude" [("Maya", 1), ("Liam", 1)] | ("Liam", 1) | " Liam" [("Maya", 1)] | ("Maya", 1) | " Maya"Every employee enters and leaves the stack once, and
"Gabe"'s full reporting chain completes before"Liam"is popped.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import json import urllib.request # ---------- Task 1: Transit stops from API JSON ---------- def text_field(stop: Dict[str, Any], key: str) -> str: """Extract stop[key] as a string, converting missing keys or JSON null into ''.""" value = stop.get(key) # Both a missing key and {"description": null} arrive as None in Python. if value is None: return "" return str(value) def format_stops(response_body: str) -> List[str]: """Parse API JSON text and format one '<name> - <description>' line per stop.""" payload = json.loads(response_body) # Guard against a missing or null "stops" list. stops = payload.get("stops") or [] lines: List[str] = [] for stop in stops: name = text_field(stop, "name") description = text_field(stop, "description") # Keep the " - " separator even when description is empty (e.g., "North Gate - "). lines.append(f"{name} - {description}") return lines def fetch_stops(url: str, timeout_seconds: float = 5.0) -> List[str]: """Perform the HTTP GET request with a timeout and format the returned stops.""" # Separated from format_stops so the offline judge can test JSON parsing without network I/O. with urllib.request.urlopen(url, timeout=timeout_seconds) as response: body = response.read().decode("utf-8") return format_stops(body) # ---------- Task 2: Org chart from CSV rows ---------- def build_reports(rows: List[List[str]]) -> Tuple[List[str], Dict[str, List[str]]]: """Group CSV rows into sorted top-level leaders and a manager -> sorted direct reports map.""" # leaders: sorted list of top-level employee names (rows where manager_name == "") leaders: List[str] = [] # direct_reports: maps manager_name -> sorted list of direct report employee names direct_reports: Dict[str, List[str]] = {} # Phase 1: Scan all n rows once in O(n) time to group every employee under their manager. for row in rows: employee_name = row[0].strip() manager_name = row[3].strip() if len(row) > 3 else "" if manager_name == "": leaders.append(employee_name) else: if manager_name not in direct_reports: direct_reports[manager_name] = [] direct_reports[manager_name].append(employee_name) # Phase 2: Sort leaders and each manager's direct report list lexicographically. leaders.sort() for report_list in direct_reports.values(): report_list.sort() return leaders, direct_reports def org_chart_lines(rows: List[List[str]]) -> List[str]: """Build the indented org chart using iterative pre-order DFS.""" leaders, direct_reports = build_reports(rows) lines: List[str] = [] # Phase 3: Iterative pre-order DFS using an explicit LIFO stack of (employee_name, depth) # so deep chains (e.g., 3,000 levels) never hit Python's ~1,000-call recursion limit. stack: List[Tuple[str, int]] = [] for leader in reversed(leaders): stack.append((leader, 0)) while stack: employee_name, depth = stack.pop() indent = " " * depth lines.append(indent + employee_name) # Push direct reports in reverse order so the alphabetically first report sits on top # of the LIFO stack and gets popped next. children = direct_reports.get(employee_name, []) for report_name in reversed(children): stack.append((report_name, depth + 1)) return lines def parse_api_json_and_org_chart(response_body: str, rows: List[List[str]]) -> Dict[str, List[str]]: return { "stops": format_stops(response_body), "org_chart": org_chart_lines(rows), }✅ Submit now — all tests should pass.
Intuition & how it works
Part 1 is a defensive JSON formatter: decode the response string once and normalize missing or null optional fields into "" before joining each station as "<name> - <description>". Part 2 works like sorting shuffled staff cards into labeled manager folders: scan the rows once to drop each employee's name into a folder keyed by their manager — an adjacency list (a dictionary mapping each parent node to its list of direct children). Next, sort every folder alphabetically and traverse the hierarchy using pre-order depth-first search (DFS) (visiting a manager and their entire sub-organization from top to bottom before moving to the manager's next sibling), driven by an explicit LIFO stack (last-in, first-out — a list where the most recently pushed item is popped next).
Naive shortcuts fail on both correctness and runtime. In Part 1, interpolating stop.get("description") without checking for None turns omitted or null descriptions into "North Gate - None". In Part 2, scanning all n rows anew to find each manager's direct reports performs n full scans (O(n²) total work), and writing DFS recursively hits Python's ~1,000-frame call-stack limit on deep reporting chains.
Trace Example 2 (stops with "Civic Plaza" having "", "North Gate" omitting "description", and "West Loop" having null; rows for Nora, Theo -> Nora, Dina -> Nora, Eli -> Dina):
- Part 1:
text_fieldturns"", missing"description", andnullinto"", producing["Civic Plaza - ", "North Gate - ", "West Loop - "]. - Part 2: Grouping and sorting builds
leaders = ["Nora"]anddirect_reports = {"Nora": ["Dina", "Theo"], "Dina": ["Eli"]}. Popping("Nora", 0)emits"Nora"and pushes("Theo", 1)then("Dina", 1); popping("Dina", 1)emits" Dina"and pushes("Eli", 2); popping("Eli", 2)emits" Eli"; finally popping("Theo", 1)emits" Theo".
Complexity
Let B be the byte/character length of response_body, S the number of station entries, and n the number of personnel rows.
- Part 1 time & space:
O(B + S)(withS <= B).json.loadsparses theB-character payload in one pass, and the loop visits each of theSstation objects inO(1)time to buildSformatted strings. - Part 2 time:
O(n log n)for grouping, sorting, and tree traversal (plusO(total output characters)to allocate the indented strings). One scan overrowsinserts each of thenemployees intoleadersordirect_reportsinO(1)average hash-table time (O(n)total). Sorting disjoint report lists of sizesk_1, k_2, ...wheresum(k_i) = nperformssum(k_i log k_i) <= n log nstring comparisons, and the stack pushes and pops each employee once (O(n)). - Part 2 space:
O(n)auxiliary memory (beyond output strings).leaders,direct_reports, andstackstore at mostnemployee names combined.
Edge cases
- Missing,
null, or emptydescription: All three normalize to""while keeping the" - "separator ("Civic Plaza - ","North Gate - ","West Loop - "). - Multiple top-level leaders or empty inputs: Multiple executives with
manager_name == ""sort alphabetically at depth0(Example 3), and empty inputs cleanly return[]. - Arbitrary row order: Because
build_reportsconsumes all rows before traversal starts, reports listed ahead of their managers still attach to the right subtree. - Single executive (
[["Solo", "Founder", "Exec", ""]]): Produces["Solo"]with zero leading spaces. - Deep reporting chain (
3,000+levels): Iterative DFS stores(employee_name, depth)tuples on a heap-allocatedlistrather than Python call frames, avoidingRecursionError. - Lexicographic case ordering: Standard string comparison places uppercase letters ahead of lowercase (
"Alec","Zane","tara"). Clarify in an interview whether case-insensitive sorting (key=str.lower) is preferred. - Surrounding whitespace or 3-column leader rows: Calling
.strip()trims" Clara "cleanly, and checkinglen(row) > 3treats a 3-column row asmanager_name == "".
Common mistakes
- Interpolating
Noneliterally in Part 1: Writingf"{stop['name']} - {stop.get('description')}"produces"North Gate - None"whenever"description"is omitted ornull. - Dropping
" - "whendescriptionis blank: Example 2 requires"Civic Plaza - ", not"Civic Plaza". - Traversing with breadth-first search (BFS): A FIFO queue outputs all depth-1 VPs before any depth-2 reports (
Clara,Gabe,Liam,Maya,Iris,Jude), breaking the visual nesting under each manager. - Pushing children in forward sorted order: Pushing
["Gabe", "Liam", "Maya"]onto a LIFO stack pops"Maya"first and reverses sibling order at every level; always pushreversed(children). - Filtering
rowsinside the traversal (O(n²)): Scanningrowsper manager times out on large organizations; builddirect_reportsonce up front.
Follow-up questions
- How would you harden the HTTP stop fetcher for a production service? Enforce explicit connect and read timeouts on every request, and retry only transient failures (socket timeouts,
HTTP 429, and502/503/504) with exponential backoff and jitter (doubling delays such as0.2s, 0.4s, 0.8splus small random jitter so clients do not synchronize retries) — safe because HTTPGETis idempotent (repeating the call produces the same result without mutating server state), while400/404errors should fail immediately. ValidateHTTP 200,Content-Type, and payload types so malformed JSON or missing"name"keys raise structured domain errors instead of rawKeyErrorcrashes, follow pagination tokens (next_cursororLinkheaders) across pages, record latency/error metrics, and unit-testformat_stopsoffline separately from HTTP client tests. - How should the hierarchy builder behave if input rows contain reporting cycles or unknown manager references? Track
all_employees = set()while scanning column0, and check that every non-emptymanager_namebelongs toall_employees(either raising a clear validation error or attaching orphaned records under a synthetic root). A cycle such asA -> B -> Ahas nomanager_name == ""root and would otherwise vanish silently fromlines: guard against both disconnected cycles and infinite loops by maintaining avisitedset before pushing ontostackand verifyinglen(lines) == len(all_employees)once traversal finishes. - What changes are needed when multiple employees share an identical name or the input file exceeds available RAM? Key the hierarchy by unique
employee_idandmanager_ididentifiers rather than display names so two"Alex Kim"employees never collide indirect_reports, sorting siblings by(employee_name, employee_id). If the CSV has tens of millions of records and cannot fit in memory, stream records lazily viacsv.readerinto an on-disk SQLite or B-tree table indexed on(manager_id, employee_name, employee_id)so iterative DFS queries one manager's sorted direct reports at a time without loading the full table into RAM.
Follow-up questions
- How would you harden the HTTP stop fetcher for a production service?
- How should the hierarchy builder behave if input rows contain reporting cycles or unknown manager references?
- What changes are needed when multiple employees share an identical name or the input file exceeds available RAM?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array