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
- Per-step timestamp ordering: Each
step_idretains the state of the event with the strictly highesttimestampobserved for thatstep_id. Any incoming event whosetimestampis less than or equal to (<=) the step's storedtimestampis stale and ignored completely. Timestamps are compared independently perstep_id. - Parent links & reparenting: A step has at most one parent (
parent_idorNone). When a newer event changes a step'sparent_id, that step—together with all of its descendants—moves under the new parent (or becomes a root whenparent_idisNone). - Unseen parents (orphans): An event may name a
parent_idthat 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 inget_tree()until an event forparent_idarrives—at which point the child automatically appears underneathparent_id. - Cycle rejection with partial update: If setting
parent_idforstep_idwould form a loop (eitherstep_id == parent_idorstep_idis already an ancestor ofparent_id, including via unseen intermediate parents), reject only the parent change: preservestep_id's previous valid parent (Noneif this isstep_id's first event), append a descriptive message toself.errors, and still updatestep_id'sstatusandtimestamp. - Queries & nested snapshot format:
get_status(step_id: str) -> Optional[str]returns thestatusfromstep_id's latest accepted event, orNoneifstep_idhas never been seen.get_tree() -> dictreturns{root_id: [children...]}over all seen steps, with top-level root keys and every child list sorted in ascending lexicographical order bystep_id. Inside any child list, represent a child that has no children as its barestrID, 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_idstrings are non-empty; each step has at most one active parent at any time.- Events arrive sequentially at
update(), with arbitrary integertimestampvalues. update(event)should run inO(depth)expected time (walking ancestor links rather than rebuilding the forest), andget_tree()should run inO(n log n)time fornseen steps.
Step-by-step walkthrough
Understand the rules and output format
We receive workflow
StepUpdatedictionaries 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_idkeeps the state from the highesttimestampseen for that step. Any incoming event whosetimestampis 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 namingparent_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 ofget_tree()as a root; the moment"build"arrives,"compile"hangs under"build"automatically. - Partial rejection on a cycle: If assigning
proposed_parenttostep_idwould create a loop (includingstep_idnaming itself as its own parent), we log an error inself.errorsand keepstep_id's previous valid parent, but we still apply the event's newerstatusandtimestamp. - 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- Newest timestamp per step wins: Each
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 allnsteps 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() callIn a live workflow UI,
get_tree()may be polled constantly while thousands of steps emit updates. Maintaining the parent and child links incrementally duringupdate()reduces each update toO(depth)time and eachget_tree()call toO(n log n)time (just sorting sibling IDs while visiting each step once).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 inO(1)average time:latest_event: mapsstep_id -> dictfor the highest-timestamp event currently in effect (used for timestamp comparisons andget_status()).parent_of: mapsstep_id -> parent_id | Nonefor upward walks during cycle detection and root checks. Crucially,parent_idis allowed to name a step not yet inlatest_event.children_of: mapsparent_id -> set of child step_idsfor downward walks duringget_tree(). Even an unseenparent_idcan already hold waiting children inchildren_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] = []Handle timestamps and partial rejection in update
Each call to
update(event)runs in three short phases:- Filter stale updates: Look up
self.latest_event.get(step_id). If an event already exists withtimestamp <= current_event["timestamp"], return immediately so older or duplicate updates cannot overwrite newer state. - Validate parent changes: Compare
proposed_parentagainstold_parent. If it changed andproposed_parentis notNone, checkself._creates_cycle(step_id, proposed_parent). On a cycle, append toself.errorsand fall back toeffective_parent = old_parent; otherwise move the step in the forest. - Record effective state: Save a shallow copy of
eventwith"parent_id"set toeffective_parentsolatest_eventalways 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- Filter stale updates: Look up
Detect cycles by walking upward through parent links
When does setting
parent_of[step_id] = candidate_parentcreate a cycle? Because our existing links never contain a cycle, adding one new link fromstep_idup tocandidate_parentcan close a loop if and only ifstep_idis alreadycandidate_parentitself or an ancestor ofcandidate_parent.Instead of searching downward through
step_id's entire subtree (which could contain thousands of descendants), we walk upward along singleparent_ofpointers starting atcandidate_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_ofwithout checkinglatest_eventis essential:"B"already recordedparent_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 atNone.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 FalseMove subtrees in O(1) time by updating two links
When
step_idchanges parent fromold_parenttonew_parent, we do not need to touch any ofstep_id's children or grandchildren. Because descendants point atstep_id(not at the root), detachingstep_idfromchildren_of[old_parent]and addingstep_idtochildren_of[new_parent]carries its entire subtree along inO(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 CIf
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)Build the sorted forest snapshot
Which steps belong at the top level of
get_tree()? Every known step inself.latest_eventwhoseparent_idis eitherNone(a true root) or not inself.latest_event(an orphan whose parent has not arrived yet). From each sorted root,_build_children_listwalks downward throughsorted(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_outputTrace 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"]}Complete solution
Putting all methods together gives the complete
ProgressTrackerimplementation: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:
"compile"arrives (parent="build",timestamp=20,status="running"):parent_of["compile"] = "build"andchildren_of["build"] = {"compile"}. Because"build"is not inlatest_eventyet,"compile"is an orphan (a step whose parent has not been seen yet), soget_tree()shows{"compile": []}."build"arrives (parent=None,timestamp=12,status="running"): timestamps are compared per step, sotimestamp=12is accepted as"build"'s first event. Now"build"is inlatest_event, soget_tree()immediately shows{"build": ["compile"]}.- Stale
"compile"arrives (parent=None,timestamp=15,status="queued"):15 <= 20, soupdate()ignores it completely. "build"arrives (parent="compile",timestamp=25,status="done"): climbing upward from"compile"visits"compile" -> "build", hittingstep_id = "build"! We append an error toself.errors, keep"build"'s old parent (None), and still update"build"'s status to"done".
Complexity
update(event)time —O(d), wheredis the depth ofproposed_parent(O(n)worst case): Dictionary and set lookups/updates takeO(1)average time, and_creates_cyclewalks upward alongparent_ofpointers at mostdhops to a root (which is small in balanced trees and at mostnin a single long chain).get_status(step_id)time —O(1)average: It performs a single dictionary lookup inself.latest_event.get_tree()time —O(n log n)fornknown steps: Each of thenknown steps is visited once as a root or child, and sorting the root IDs plus each node's child set addsO(n log n)total comparisons across all levels (O(n)temporary space for the returned nested dictionary).- Persistent space —
O(n): Each of thenknown steps stores one entry inlatest_event, at most one entry inparent_of, and belongs to at most one set inchildren_of(because empty sets inchildren_ofare deleted when steps move), plus one string per rejected cycle inerrors.
Edge cases
- Self-parent (
step_id == parent_id):_creates_cycle("A", "A")seesancestor == step_idon the very first check (0hops), logs an error, preserves the previous parent (Noneif brand-new), and still updatesstatusandtimestamp. - Parent ID that never arrives: If
"B"points to"ghost"and"ghost"never sends an event,"ghost"is never invented as a node inlatest_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"followsparent_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 callsupdate()first wins the link and the second is rejected as a cycle. - Very deep linear chains (
> 1,000steps):_build_children_listuses recursion once per tree level, which could hit Python's default recursion limit on chains deeper than1,000; converting it to an explicit stack avoidsRecursionErrorif extreme depths are expected.
Common mistakes
- Walking downward through
step_id's subtree instead of upward fromproposed_parent. Both detect cycles, but a root step can have10,000descendants 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_eventinstead ofwhile ancestor is not Nonemisses 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
statusandtimestampmust 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_idfromchildren_of[old_parent]when reparenting, causing moved steps to appear in two places at once inget_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
dirtyflag. Wheneverupdate()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 asdirty(O(depth)nodes). Thenget_tree()recomputes onlydirtynodes 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()readslatest_event, walksparent_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 runningupdate(A -> B)andupdate(B -> A)from both passing_creates_cyclesimultaneously and creating a loop. Wrap the entire body ofupdate(),get_status(), andget_tree()inside a singlethreading.Lockso 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 aSet[str]. Cycle detection when adding parentPtoScan 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 avisitedset) over all ancestors ofP, costingO(V + E)in the worst case. In addition, a nested dictionary tree would duplicate shared subtrees exponentially in a diamond-shaped DAG, soget_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
- 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()?
- How would you make ProgressTracker safe under concurrent multi-threaded update() and get_tree() calls without allowing race-condition cycles?
- How would your data structures, cycle check, and snapshot representation change if each step could depend on multiple parents (a DAG)?
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