Live Workflow Hierarchy from Out-of-Order Updates

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement ProgressTracker to maintain a live hierarchy of workflow steps from an asynchronous event stream where packets can arrive out of timestamp order, reference parents whose own events have not arrived yet, or propose invalid cyclic parent links.

Each incoming event is a dictionary with four fields:

{"step_id": str, "status": str, "parent_id": str | None, "timestamp": int}

Behavioral Rules

  1. Per-step timestamp ordering: Each step_id retains the state of the event with the strictly highest timestamp observed for that step_id. Any incoming event whose timestamp is less than or equal to (<=) the step's stored timestamp is stale and ignored completely. Timestamps are compared independently per step_id.
  2. Parent links & reparenting: A step has at most one parent (parent_id or None). When a newer event changes a step's parent_id, that step—together with all of its descendants—moves under the new parent (or becomes a root when parent_id is None).
  3. Unseen parents (orphans): An event may name a parent_id that has not sent any event yet (or never sends one). Record that link immediately, do not fabricate an unseen node, and display the child as a top-level root in get_tree() until an event for parent_id arrives—at which point the child automatically appears underneath parent_id.
  4. Cycle rejection with partial update: If setting parent_id for step_id would form a loop (either step_id == parent_id or step_id is already an ancestor of parent_id, including via unseen intermediate parents), reject only the parent change: preserve step_id's previous valid parent (None if this is step_id's first event), append a descriptive message to self.errors, and still update step_id's status and timestamp.
  5. Queries & nested snapshot format:
    • get_status(step_id: str) -> Optional[str] returns the status from step_id's latest accepted event, or None if step_id has never been seen.
    • get_tree() -> dict returns {root_id: [children...]} over all seen steps, with top-level root keys and every child list sorted in ascending lexicographical order by step_id. Inside any child list, represent a child that has no children as its bare str ID, and represent a child that has children as {child_id: [its_children...]}. A root with no children maps to [].
from typing import Dict, List, Optional

class ProgressTracker:
    def __init__(self) -> None:
        self.errors: List[str] = []

    def update(self, event: dict) -> None: ...
    def get_status(self, step_id: str) -> Optional[str]: ...
    def get_tree(self) -> dict: ...

Examples

Example 1

tracker = ProgressTracker()
tracker.update({"step_id": "compile", "status": "running", "parent_id": "build", "timestamp": 20})
tracker.get_tree()
# -> {"compile": []}   ("build" has not arrived yet, so "compile" waits as a root)

tracker.update({"step_id": "build", "status": "running", "parent_id": None, "timestamp": 12})
tracker.get_tree()
# -> {"build": ["compile"]}

tracker.update({"step_id": "compile", "status": "queued", "parent_id": None, "timestamp": 15})
tracker.get_tree()
# -> {"build": ["compile"]}   (15 <= 20 for "compile", so stale packet is ignored)

Walk-through: "compile" arrives first pointing to unseen "build", so it temporarily appears at the top level. When "build" arrives with timestamp = 12 (accepted because "build" had no prior event), "compile" attaches underneath "build". The third packet has timestamp = 15 <= 20 for "compile" and is discarded.

Example 2

tracker = ProgressTracker()
tracker.update({"step_id": "deploy", "status": "queued", "parent_id": None, "timestamp": 1})
tracker.update({"step_id": "lint", "status": "done", "parent_id": "ci", "timestamp": 2})
tracker.update({"step_id": "test", "status": "running", "parent_id": "ci", "timestamp": 3})
tracker.update({"step_id": "unit", "status": "running", "parent_id": "test", "timestamp": 4})
tracker.update({"step_id": "ci", "status": "running", "parent_id": None, "timestamp": 5})
tracker.update({"step_id": "ci", "status": "done", "parent_id": "unit", "timestamp": 6})

tracker.get_tree()        # -> {"ci": ["lint", {"test": ["unit"]}], "deploy": []}
tracker.get_status("ci")  # -> "done"
len(tracker.errors)       # -> 1

Walk-through: After event 5, "ci" has leaf child "lint" and branch child {"test": ["unit"]}, while "deploy" is a childless root. Event 6 tries to place "ci" under its own descendant "unit": the cyclic parent link is rejected and logged in tracker.errors (keeping "ci" as a root), while "ci"'s newer status = "done" and timestamp = 6 still take effect.

Constraints

  • step_id strings are non-empty; each step has at most one active parent at any time.
  • Events arrive sequentially at update(), with arbitrary integer timestamp values.
  • update(event) should run in O(depth) expected time (walking ancestor links rather than rebuilding the forest), and get_tree() should run in O(n log n) time for n seen steps.

Step-by-step walkthrough

  1. Understand the rules and output format

    We receive workflow StepUpdate dictionaries of the form {"step_id": str, "status": str, "parent_id": str | None, "timestamp": int} in arbitrary network order, and we must maintain a forest (a collection of disjoint trees) of valid parent-child relationships.

    Before writing code, let's pin down four exact behavioral rules from the specification and starter.py:

    • Newest timestamp per step wins: Each step_id keeps the state from the highest timestamp seen for that step. Any incoming event whose timestamp is less than or equal to (<=) the step's currently stored timestamp is stale and completely ignored.
    • Orphans wait as temporary roots: If step "compile" arrives naming parent_id = "build", we remember that link immediately, even if "build" has never sent an event yet. Until "build" arrives, "compile" appears at the top level of get_tree() as a root; the moment "build" arrives, "compile" hangs under "build" automatically.
    • Partial rejection on a cycle: If assigning proposed_parent to step_id would create a loop (including step_id naming itself as its own parent), we log an error in self.errors and keep step_id's previous valid parent, but we still apply the event's newer status and timestamp.
    • Deterministic nested output: Top-level roots map to a sorted list of their children. Inside a child list, a leaf (a step with no children) is written as its bare string ID, while an internal branch (a step that has children of its own) is written as {child_id: [its_children]}:
    Forest structure:                     get_tree() output:
          ci          deploy              {
         /  \                             "ci": ["lint", {"test": ["unit"]}],
      lint  test                          "deploy": []
             |                            }
            unit
    
  2. Why rebuilding from scratch on every snapshot is too slow

    A naive implementation appends every raw event to a list and rebuilds the entire forest inside get_tree() whenever a dashboard polls for progress: find each step's highest-timestamp event, replay parent links with cycle checks, and scan all n steps to find every node's children.

    Naive snapshot cost for E events and n steps:
      replay E events * O(depth) + scan n steps per node = O(E * depth + n^2) per get_tree() call
    

    In a live workflow UI, get_tree() may be polled constantly while thousands of steps emit updates. Maintaining the parent and child links incrementally during update() reduces each update to O(depth) time and each get_tree() call to O(n log n) time (just sorting sibling IDs while visiting each step once).

  3. Design the four state maps

    To update links and build snapshots without full-table scans, we store four fields on ProgressTracker, each answering one lookup in O(1) average time:

    • latest_event: maps step_id -> dict for the highest-timestamp event currently in effect (used for timestamp comparisons and get_status()).
    • parent_of: maps step_id -> parent_id | None for upward walks during cycle detection and root checks. Crucially, parent_id is allowed to name a step not yet in latest_event.
    • children_of: maps parent_id -> set of child step_ids for downward walks during get_tree(). Even an unseen parent_id can already hold waiting children in children_of[parent_id].
    • errors: list of human-readable strings appended whenever a cyclic parent link is rejected.
    from typing import Dict, List, Optional, Set
    
    
    class ProgressTracker:
        """Maintains the latest state of every workflow step and their valid parent-child forest."""
    
        def __init__(self) -> None:
            # latest_event: step_id -> accepted event dict with highest timestamp seen so far,
            # e.g. {"step_id": "compile", "status": "running", "parent_id": "build", "timestamp": 20}
            self.latest_event: Dict[str, dict] = {}
    
            # parent_of: step_id -> current accepted parent_id (or None if root);
            # may reference a parent_id whose own event has not arrived yet
            self.parent_of: Dict[str, Optional[str]] = {}
    
            # children_of: parent_id -> set of child step_ids currently pointing to parent_id,
            # e.g. {"ci": {"lint", "test"}}; lets get_tree() walk top-down without scanning all steps
            self.children_of: Dict[str, Set[str]] = {}
    
            # errors: log messages recorded whenever a cyclic parent assignment is rejected
            self.errors: List[str] = []
    
  4. Handle timestamps and partial rejection in update

    Each call to update(event) runs in three short phases:

    1. Filter stale updates: Look up self.latest_event.get(step_id). If an event already exists with timestamp <= current_event["timestamp"], return immediately so older or duplicate updates cannot overwrite newer state.
    2. Validate parent changes: Compare proposed_parent against old_parent. If it changed and proposed_parent is not None, check self._creates_cycle(step_id, proposed_parent). On a cycle, append to self.errors and fall back to effective_parent = old_parent; otherwise move the step in the forest.
    3. Record effective state: Save a shallow copy of event with "parent_id" set to effective_parent so latest_event always reflects the parent that actually took effect.
        def update(self, event: dict) -> None:
            step_id = event["step_id"]
            timestamp = event["timestamp"]
    
            # Phase 1: Enforce last-writer-wins by event timestamp.
            # Use <= so both late-arriving older events and duplicate-timestamp events are ignored.
            current_event = self.latest_event.get(step_id)
            if current_event is not None and timestamp <= current_event["timestamp"]:
                return
    
            # Phase 2: Validate and apply any parent change.
            old_parent = self.parent_of.get(step_id)
            proposed_parent = event.get("parent_id")
            effective_parent = proposed_parent
    
            if proposed_parent != old_parent:
                if proposed_parent is not None and self._creates_cycle(step_id, proposed_parent):
                    # Reject only the cyclic parent link: keep old_parent, but still record
                    # the newer status and timestamp below as required by the specification.
                    self.errors.append(
                        f"cycle: {proposed_parent} as parent of {step_id} ignored (timestamp {timestamp})"
                    )
                    effective_parent = old_parent
                else:
                    self._move_step(step_id, old_parent, proposed_parent)
    
            # Phase 3: Store a copy of the event carrying the parent_id actually in effect.
            stored_event = dict(event)
            stored_event["parent_id"] = effective_parent
            self.latest_event[step_id] = stored_event
    
  5. Detect cycles by walking upward through parent links

    When does setting parent_of[step_id] = candidate_parent create a cycle? Because our existing links never contain a cycle, adding one new link from step_id up to candidate_parent can close a loop if and only if step_id is already candidate_parent itself or an ancestor of candidate_parent.

    Instead of searching downward through step_id's entire subtree (which could contain thousands of descendants), we walk upward along single parent_of pointers starting at candidate_parent:

    Existing chain:  A (root) <-- B <-- C     Proposal: make C the parent of A (A -> parent C)
    
    Walk upward starting at candidate_parent = C:
      ancestor = C   (C != A, keep climbing via parent_of["C"])
      ancestor = B   (B != A, keep climbing via parent_of["B"])
      ancestor = A   (A == step_id -> CYCLE DETECTED! Reject link.)
    
    Unseen-step case: B arrived earlier with parent_of["B"] = "A" ("A" not seen yet).
    Now "A" arrives proposing parent "B":
      ancestor = B -> parent_of["B"] is "A" == step_id -> CYCLE DETECTED!
    

    Notice why following self.parent_of without checking latest_event is essential: "B" already recorded parent_of["B"] = "A" before "A" arrived, and following that stored pointer catches the two-node loop "A" <-> "B" immediately. And because accepted links are always acyclic, this upward walk is guaranteed to terminate at None.

        def _creates_cycle(self, step_id: str, candidate_parent: str) -> bool:
            """Return True if step_id is candidate_parent itself or an ancestor of candidate_parent."""
            # Walk upward from candidate_parent toward its root. Even unseen intermediate parents
            # are followed via self.parent_of so cycles through not-yet-seen steps are caught.
            ancestor: Optional[str] = candidate_parent
            while ancestor is not None:
                if ancestor == step_id:
                    return True
                ancestor = self.parent_of.get(ancestor)
            return False
    
  6. Move subtrees in O(1) time by updating two links

    When step_id changes parent from old_parent to new_parent, we do not need to touch any of step_id's children or grandchildren. Because descendants point at step_id (not at the root), detaching step_id from children_of[old_parent] and adding step_id to children_of[new_parent] carries its entire subtree along in O(1) time:

    Before moving B from A to D:        After detaching B from A and attaching B to D:
        A           D                       A           D
        |                                               |
        B                                               B
        |                                               |
        C                                               C
    

    If children_of[old_parent] becomes empty, deleting that key ensures abandoned unseen parent IDs never accumulate in memory.

        def _move_step(
            self,
            step_id: str,
            old_parent: Optional[str],
            new_parent: Optional[str],
        ) -> None:
            """Detach step_id from old_parent and attach it under new_parent."""
            if old_parent is not None and old_parent in self.children_of:
                self.children_of[old_parent].discard(step_id)
                # Clean up empty child sets so abandoned unseen parent IDs never leak memory.
                if not self.children_of[old_parent]:
                    del self.children_of[old_parent]
    
            self.parent_of[step_id] = new_parent
    
            if new_parent is not None:
                if new_parent not in self.children_of:
                    self.children_of[new_parent] = set()
                self.children_of[new_parent].add(step_id)
    
  7. Build the sorted forest snapshot

    Which steps belong at the top level of get_tree()? Every known step in self.latest_event whose parent_id is either None (a true root) or not in self.latest_event (an orphan whose parent has not arrived yet). From each sorted root, _build_children_list walks downward through sorted(self.children_of.get(step_id, set())), returning bare IDs for leaves and {child_id: grandchildren} dictionaries for branches.

        def get_status(self, step_id: str) -> Optional[str]:
            """Return status from the step's latest accepted event, or None if unknown."""
            event = self.latest_event.get(step_id)
            if event is None:
                return None
            return event.get("status")
    
        def get_tree(self) -> dict:
            """Return the current valid forest sorted by step_id at every level."""
            forest = {}
            for step_id in sorted(self.latest_event):
                parent_id = self.parent_of.get(step_id)
                # A step is a top-level root if it has no parent OR if its parent has not
                # appeared in any event yet (an orphan waiting for its parent to arrive).
                if parent_id is None or parent_id not in self.latest_event:
                    forest[step_id] = self._build_children_list(step_id)
            return forest
    
        def _build_children_list(self, step_id: str) -> list:
            """Build sorted children of step_id: bare step_id for leaves, {step_id: [...]} for branches."""
            children_output = []
            # Every child_id in children_of was added during update(), so it is a known step.
            for child_id in sorted(self.children_of.get(step_id, set())):
                grandchildren = self._build_children_list(child_id)
                if grandchildren:
                    children_output.append({child_id: grandchildren})
                else:
                    children_output.append(child_id)
            return children_output
    

    Trace Example 1 step by step to see how "compile" transitions smoothly from temporary orphan root to child of "build" with zero extra rewiring when "build" arrives, and why a late packet is discarded:

    1. update({"step_id": "compile", "status": "running", "parent_id": "build", "timestamp": 20})
       latest_event = {"compile": ...}
       parent_of    = {"compile": "build"}
       children_of  = {"build": {"compile"}}    <- "compile" is already pre-registered under "build"!
       get_tree()   -> "build" not in latest_event, so "compile" is a root -> {"compile": []}
    
    2. update({"step_id": "build", "status": "running", "parent_id": None, "timestamp": 12})
       latest_event = {"compile": ..., "build": ...}
       parent_of    = {"compile": "build", "build": None}  <- ts 12 is "build"'s first event, so accepted!
       children_of  = {"build": {"compile"}}
       get_tree()   -> "build" is a root with child "compile" -> {"build": ["compile"]}
    
    3. update({"step_id": "compile", "status": "queued", "parent_id": None, "timestamp": 15})
       15 <= latest_event["compile"]["timestamp"] (20) -> stale packet ignored; tree stays {"build": ["compile"]}
    
  8. Complete solution

    Putting all methods together gives the complete ProgressTracker implementation:

    from typing import Dict, List, Optional, Set
    
    
    class ProgressTracker:
        """Maintains the latest state of every workflow step and their valid parent-child forest."""
    
        def __init__(self) -> None:
            # latest_event: step_id -> accepted event dict with highest timestamp seen so far,
            # e.g. {"step_id": "compile", "status": "running", "parent_id": "build", "timestamp": 20}
            self.latest_event: Dict[str, dict] = {}
    
            # parent_of: step_id -> current accepted parent_id (or None if root);
            # may reference a parent_id whose own event has not arrived yet
            self.parent_of: Dict[str, Optional[str]] = {}
    
            # children_of: parent_id -> set of child step_ids currently pointing to parent_id,
            # e.g. {"ci": {"lint", "test"}}; lets get_tree() walk top-down without scanning all steps
            self.children_of: Dict[str, Set[str]] = {}
    
            # errors: log messages recorded whenever a cyclic parent assignment is rejected
            self.errors: List[str] = []
    
        def update(self, event: dict) -> None:
            step_id = event["step_id"]
            timestamp = event["timestamp"]
    
            # Phase 1: Enforce last-writer-wins by event timestamp.
            # Use <= so both late-arriving older events and duplicate-timestamp events are ignored.
            current_event = self.latest_event.get(step_id)
            if current_event is not None and timestamp <= current_event["timestamp"]:
                return
    
            # Phase 2: Validate and apply any parent change.
            old_parent = self.parent_of.get(step_id)
            proposed_parent = event.get("parent_id")
            effective_parent = proposed_parent
    
            if proposed_parent != old_parent:
                if proposed_parent is not None and self._creates_cycle(step_id, proposed_parent):
                    # Reject only the cyclic parent link: keep old_parent, but still record
                    # the newer status and timestamp below as required by the specification.
                    self.errors.append(
                        f"cycle: {proposed_parent} as parent of {step_id} ignored (timestamp {timestamp})"
                    )
                    effective_parent = old_parent
                else:
                    self._move_step(step_id, old_parent, proposed_parent)
    
            # Phase 3: Store a copy of the event carrying the parent_id actually in effect.
            stored_event = dict(event)
            stored_event["parent_id"] = effective_parent
            self.latest_event[step_id] = stored_event
    
        def _creates_cycle(self, step_id: str, candidate_parent: str) -> bool:
            """Return True if step_id is candidate_parent itself or an ancestor of candidate_parent."""
            # Walk upward from candidate_parent toward its root. Even unseen intermediate parents
            # are followed via self.parent_of so cycles through not-yet-seen steps are caught.
            ancestor: Optional[str] = candidate_parent
            while ancestor is not None:
                if ancestor == step_id:
                    return True
                ancestor = self.parent_of.get(ancestor)
            return False
    
        def _move_step(
            self,
            step_id: str,
            old_parent: Optional[str],
            new_parent: Optional[str],
        ) -> None:
            """Detach step_id from old_parent and attach it under new_parent."""
            if old_parent is not None and old_parent in self.children_of:
                self.children_of[old_parent].discard(step_id)
                # Clean up empty child sets so abandoned unseen parent IDs never leak memory.
                if not self.children_of[old_parent]:
                    del self.children_of[old_parent]
    
            self.parent_of[step_id] = new_parent
    
            if new_parent is not None:
                if new_parent not in self.children_of:
                    self.children_of[new_parent] = set()
                self.children_of[new_parent].add(step_id)
    
        def get_status(self, step_id: str) -> Optional[str]:
            """Return status from the step's latest accepted event, or None if unknown."""
            event = self.latest_event.get(step_id)
            if event is None:
                return None
            return event.get("status")
    
        def get_tree(self) -> dict:
            """Return the current valid forest sorted by step_id at every level."""
            forest = {}
            for step_id in sorted(self.latest_event):
                parent_id = self.parent_of.get(step_id)
                # A step is a top-level root if it has no parent OR if its parent has not
                # appeared in any event yet (an orphan waiting for its parent to arrive).
                if parent_id is None or parent_id not in self.latest_event:
                    forest[step_id] = self._build_children_list(step_id)
            return forest
    
        def _build_children_list(self, step_id: str) -> list:
            """Build sorted children of step_id: bare step_id for leaves, {step_id: [...]} for branches."""
            children_output = []
            # Every child_id in children_of was added during update(), so it is a known step.
            for child_id in sorted(self.children_of.get(step_id, set())):
                grandchildren = self._build_children_list(child_id)
                if grandchildren:
                    children_output.append({child_id: grandchildren})
                else:
                    children_output.append(child_id)
            return children_output
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of building an organization chart from employee badges arriving in shuffled mail: Alice's badge might arrive on Tuesday saying "Reports to: Bob" before Bob's own badge arrives on Wednesday, and an older draft of Alice's badge might arrive late on Thursday. We handle this by keeping one "latest badge" folder per person (latest_event), plus a two-way directory of links: who each person reports to (parent_of) and a waiting-room list of direct reports under every manager name (children_of), even if that manager has not arrived yet.

A naive tracker that saves every raw event and rebuilds the entire hierarchy inside get_tree() has to replay the event stream and scan all n steps for each node, taking O(E * depth + n^2) work on every dashboard refresh. Worse, if you refuse to store links to unseen parents until those parents arrive, you need awkward waiting queues and can miss cycles that pass through not-yet-seen nodes. Storing both upward (parent_of) and downward (children_of) links incrementally lets orphans snap under their parent the instant the parent arrives, while checking for cycles (closed loops where a step becomes its own ancestor) is just a quick upward climb along parent_of pointers.

Walk through four short events to see every rule in action:

  1. "compile" arrives (parent="build", timestamp=20, status="running"): parent_of["compile"] = "build" and children_of["build"] = {"compile"}. Because "build" is not in latest_event yet, "compile" is an orphan (a step whose parent has not been seen yet), so get_tree() shows {"compile": []}.
  2. "build" arrives (parent=None, timestamp=12, status="running"): timestamps are compared per step, so timestamp=12 is accepted as "build"'s first event. Now "build" is in latest_event, so get_tree() immediately shows {"build": ["compile"]}.
  3. Stale "compile" arrives (parent=None, timestamp=15, status="queued"): 15 <= 20, so update() ignores it completely.
  4. "build" arrives (parent="compile", timestamp=25, status="done"): climbing upward from "compile" visits "compile" -> "build", hitting step_id = "build"! We append an error to self.errors, keep "build"'s old parent (None), and still update "build"'s status to "done".

Complexity

  • update(event) time — O(d), where d is the depth of proposed_parent (O(n) worst case): Dictionary and set lookups/updates take O(1) average time, and _creates_cycle walks upward along parent_of pointers at most d hops to a root (which is small in balanced trees and at most n in a single long chain).
  • get_status(step_id) time — O(1) average: It performs a single dictionary lookup in self.latest_event.
  • get_tree() time — O(n log n) for n known steps: Each of the n known steps is visited once as a root or child, and sorting the root IDs plus each node's child set adds O(n log n) total comparisons across all levels (O(n) temporary space for the returned nested dictionary).
  • Persistent space — O(n): Each of the n known steps stores one entry in latest_event, at most one entry in parent_of, and belongs to at most one set in children_of (because empty sets in children_of are deleted when steps move), plus one string per rejected cycle in errors.

Edge cases

  • Self-parent (step_id == parent_id): _creates_cycle("A", "A") sees ancestor == step_id on the very first check (0 hops), logs an error, preserves the previous parent (None if brand-new), and still updates status and timestamp.
  • Parent ID that never arrives: If "B" points to "ghost" and "ghost" never sends an event, "ghost" is never invented as a node in latest_event; "B" simply remains a top-level root with its own children intact.
  • Cycle through an unseen step: If "B" arrives pointing to unseen "A" and then "A" arrives pointing to "B", walking upward from "B" follows parent_of["B"] -> "A", catching the cycle even though "A" had no event moments earlier.
  • Duplicate or older timestamps: Comparing with timestamp <= current_event["timestamp"] ensures replayed duplicate packets neither flip parent links nor append duplicate cycle errors.
  • Arrival order between different steps: Timestamps only order updates for the same step_id. If "A" claims parent "B" and "B" claims parent "A", whichever packet calls update() first wins the link and the second is rejected as a cycle.
  • Very deep linear chains (> 1,000 steps): _build_children_list uses recursion once per tree level, which could hit Python's default recursion limit on chains deeper than 1,000; converting it to an explicit stack avoids RecursionError if extreme depths are expected.

Common mistakes

  • Walking downward through step_id's subtree instead of upward from proposed_parent. Both detect cycles, but a root step can have 10,000 descendants while a candidate parent is typically only a few hops below its root.
  • Skipping unseen steps during cycle detection. Checking while ancestor in self.latest_event instead of while ancestor is not None misses loops formed through steps whose own events have not arrived yet.
  • Dropping the entire event when a cycle occurs. The requirement says to ignore that specific parent assignment and keep the previous valid parent — the event's newer status and timestamp must still take effect.
  • Comparing against the last arrived event instead of the highest-timestamp stored event, allowing a delayed older packet to overwrite newer state.
  • Forgetting to remove step_id from children_of[old_parent] when reparenting, causing moved steps to appear in two places at once in get_tree().

Follow-up questions

  • If snapshots are requested frequently on a million-node hierarchy where each event touches only one small subtree, how would you speed up get_tree()? Cache each node's serialized subtree representation alongside a boolean dirty flag. Whenever update() changes a step's parent or introduces a previously unseen step that adopts waiting orphans, mark only the affected step, its old parent, its new parent, and their ancestors up to the roots as dirty (O(depth) nodes). Then get_tree() recomputes only dirty nodes and reuses cached immutable structures (such as tuples or frozen mappings) for untouched branches, or better yet, assigns monotonic version numbers so polling clients fetch only an incremental diff stream (the small list of nodes changed since the client's last version).
  • How would you make ProgressTracker safe under concurrent multi-threaded update() and get_tree() calls without allowing race-condition cycles? Because update() reads latest_event, walks parent_of, and mutates three dictionaries across several statements, Python's Global Interpreter Lock (GIL) (an internal interpreter mutex that protects single bytecodes, not multi-step logic) cannot stop two threads running update(A -> B) and update(B -> A) from both passing _creates_cycle simultaneously and creating a loop. Wrap the entire body of update(), get_status(), and get_tree() inside a single threading.Lock so every check-and-mutate sequence executes atomically; if write throughput becomes a bottleneck, push incoming events onto a thread-safe queue consumed by a single writer thread that periodically publishes an immutable snapshot reference for lock-free readers.
  • How would your data structures, cycle check, and snapshot representation change if each step could depend on multiple parents (a DAG)? A Directed Acyclic Graph (DAG) allows a step to depend on several parents as long as directed edges never form a closed loop, so parent_of[step_id] changes from a single string to a Set[str]. Cycle detection when adding parent P to S can no longer follow a single chain — it must run a Breadth-First Search (BFS) or Depth-First Search (DFS) (standard graph traversals using a queue or stack plus a visited set) over all ancestors of P, costing O(V + E) in the worst case. In addition, a nested dictionary tree would duplicate shared subtrees exponentially in a diamond-shaped DAG, so get_tree() should change to return a flat adjacency map {"nodes": ..., "children": {id: [...]}}, and you should define whether an event with [valid_parent, cyclic_parent] accepts the safe parent while logging the cyclic one.

Follow-up questions

Similar questions

More Ai2 interview questions

All 1 Ai2 questions →