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 JSON null value, or "" as an empty string "" (and treat a missing or null "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 having manager_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_name with " " * depth (two spaces per reporting level: 0 spaces for top-level executives, 2 spaces for their direct reports, 4 spaces at depth 2, and so on).
  • Sort top-level executives—and every manager's direct report list—in standard lexicographic (ASCII/Unicode code-point) order by employee_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_body is valid UTF-8 JSON representing a top-level object.
  • 0 <= len(rows) <= 10^5; employee names are unique within rows.
  • The manager relationship forms a cycle-free forest, and every non-empty manager_name matches some employee_name in rows.
  • Reporting chains may be thousands of levels deep, and repeated O(n^2) scans over rows are too slow; aim for O(n log n) time and O(n) space.

Step-by-step walkthrough

  1. 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_body and build one "<name> - <description>" string per station in array order. Look at Example 2: whenever description is "", null, or omitted, the " - " delimiter stays intact ("North Gate - ").
    • Part 2 (Reporting hierarchy): Each record in rows is [employee_name, title, department, manager_name]. Top-level executives have manager_name == "". Emit every manager ahead of their subtree, indent by 2 spaces per level, and sort siblings lexicographically by employee_name.

    Keeping fetch_stops(url) separate from format_stops(response_body) is good engineering practice: network I/O lives at the boundary, while string parsing remains pure and deterministic.

  2. 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:

    1. "description": "" -> stop.get("description") returns ""
    2. "description": null -> stop.get("description") returns None
    3. Key omitted entirely -> stop.get("description") returns None

    Formatting stop.get("description") directly in an f-string would turn cases 2 and 3 into "North Gate - None". A small text_field helper normalizes None to "" 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)
    
  3. Part 2: Why rescanning rows per manager takes O(n²) time

    Suppose we find "Clara" at depth 0 and scan all n records to collect everyone reporting to "Clara". Next, for "Gabe", we scan all n records a second time; then for "Iris", we scan all n records again.

    Repeating a full O(n) table scan for each of the n employees costs O(n²) work (100,000 employees would trigger 10,000,000,000 comparisons). We are re-reading the entire input just to answer "who reports directly to X?"

  4. Group direct reports in a single O(n) pass

    Instead, read rows once and bucket each employee under their manager_name in a dictionary direct_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 record direct_reports["Iris"] = ["Jude"] and connect "Iris" under "Gabe" when her row arrives. Afterward, we sort leaders and sort each manager's list once. Since every employee sits in at most one list, the list lengths sum to n and sorting all of them takes at most O(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_reports
    
  5. Emit indented lines with iterative pre-order DFS

    In Example 1, "Gabe", "Iris", and "Jude" all appear before "Liam", even though "Liam" sits at depth 1 and "Jude" sits at depth 3. 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 deep 3,000-level reporting chain and raise RecursionError. 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
    
  6. Trace Example 1 step by step

    For Example 1, leaders = ["Clara"] and direct_reports = {"Clara": ["Gabe", "Liam", "Maya"], "Gabe": ["Iris"], "Iris": ["Jude"]}. Watch the stack (top of stack on the right) across org_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.

  7. 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_field turns "", missing "description", and null into "", producing ["Civic Plaza - ", "North Gate - ", "West Loop - "].
  • Part 2: Grouping and sorting builds leaders = ["Nora"] and direct_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) (with S <= B). json.loads parses the B-character payload in one pass, and the loop visits each of the S station objects in O(1) time to build S formatted strings.
  • Part 2 time: O(n log n) for grouping, sorting, and tree traversal (plus O(total output characters) to allocate the indented strings). One scan over rows inserts each of the n employees into leaders or direct_reports in O(1) average hash-table time (O(n) total). Sorting disjoint report lists of sizes k_1, k_2, ... where sum(k_i) = n performs sum(k_i log k_i) <= n log n string 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, and stack store at most n employee names combined.

Edge cases

  • Missing, null, or empty description: 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 depth 0 (Example 3), and empty inputs cleanly return [].
  • Arbitrary row order: Because build_reports consumes 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-allocated list rather than Python call frames, avoiding RecursionError.
  • 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 checking len(row) > 3 treats a 3-column row as manager_name == "".

Common mistakes

  • Interpolating None literally in Part 1: Writing f"{stop['name']} - {stop.get('description')}" produces "North Gate - None" whenever "description" is omitted or null.
  • Dropping " - " when description is 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 push reversed(children).
  • Filtering rows inside the traversal (O(n²)): Scanning rows per manager times out on large organizations; build direct_reports once 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, and 502/503/504) with exponential backoff and jitter (doubling delays such as 0.2s, 0.4s, 0.8s plus small random jitter so clients do not synchronize retries) — safe because HTTP GET is idempotent (repeating the call produces the same result without mutating server state), while 400/404 errors should fail immediately. Validate HTTP 200, Content-Type, and payload types so malformed JSON or missing "name" keys raise structured domain errors instead of raw KeyError crashes, follow pagination tokens (next_cursor or Link headers) across pages, record latency/error metrics, and unit-test format_stops offline 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 column 0, and check that every non-empty manager_name belongs to all_employees (either raising a clear validation error or attaching orphaned records under a synthetic root). A cycle such as A -> B -> A has no manager_name == "" root and would otherwise vanish silently from lines: guard against both disconnected cycles and infinite loops by maintaining a visited set before pushing onto stack and verifying len(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_id and manager_id identifiers rather than display names so two "Alex Kim" employees never collide in direct_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 via csv.reader into 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

Similar questions

More Cortex interview questions

All 1 Cortex questions →