Dynamic Hierarchy Manager with Timestamp Ordering
Data Structure DesignModel answerLast updated
Build a system that processes timestamped parent-child updates arriving in any order, maintains a valid tree structure, and prevents cycles.
Problem
You're implementing a workflow tracking system that receives updates about task dependencies. Updates arrive as events, each containing:
step_id: unique identifier for a taskparent_id: the task this one depends on (orNonefor root tasks)timestamp: when this update was generatedstatus: current state of the task
The challenge: Events can arrive in any order. A child task's update might arrive before its parent even exists. Later events might carry older timestamps. You must maintain the correct hierarchy based on timestamp ordering.
Your Task
Implement a ProgressTracker class with two methods:
class ProgressTracker:
def update(self, event: dict) -> None:
"""Process a single event and update internal state."""
pass
def get_tree(self) -> dict:
"""Return the current hierarchy as a nested dictionary."""
pass
Rules
-
Timestamp precedence: For each
step_id, only the event with the highesttimestampdetermines its current state. Ignore events with older timestamps for steps you've already seen. -
Hierarchy constraints:
- Each step has at most one parent
- If a step references a parent that doesn't exist yet, treat it as a temporary root until the parent arrives
- When the parent arrives, automatically attach waiting children
-
Cycle prevention: If assigning a parent would create a cycle (including self-reference), reject that parent assignment but still apply the status and timestamp from the event.
-
Output format: Return a nested dictionary where each key is a
step_idand its value is a dictionary of its children. Leaf nodes map to empty dictionaries{}.
Example
tracker = ProgressTracker()
tracker.update({"step_id": "B", "parent_id": "A", "status": "running", "timestamp": 10})
tracker.update({"step_id": "A", "parent_id": None, "status": "done", "timestamp": 5})
print(tracker.get_tree())
# {"A": {"B": {}}}
tracker.update({"step_id": "C", "parent_id": "B", "status": "pending", "timestamp": 15})
print(tracker.get_tree())
# {"A": {"B": {"C": {}}}}
Edge Cases to Handle
- Self-referential parent assignments
- Parent that never appears in any event
- Reparenting a step (changing its parent via a newer timestamp)
- Events with equal timestamps (implementation choice: you decide tie-breaking)
- Deep hierarchies (avoid recursion limits)
Hints
Hint 1
Track both the latest timestamp per step and the effective parent separately - these serve different purposes
Hint 2
For cycle detection, walk ancestors upward from the proposed parent - if you reach the step being moved, you've found a cycle
Hint 3
Maintain a registry of steps waiting for parents that haven't arrived yet, indexed both by the missing parent and by the waiting child for O(1) lookups
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Dynamic Hierarchy Manager
Approach
The core challenge is separating what an event requests from what the tree actually contains. We need multiple data structures working together:
State tracking:
timestamps: Maps each step to its latest accepted timestampstatuses: Maps each step to its current statuseffective_parent: Maps each step to its actual parent in the valid tree (orNonefor roots)
Tree structure:
children: Adjacency list mapping each step to its set of children
Pending relationships:
waiting_for: Maps a not-yet-seen parent to the set of steps waiting for itpending_parent: Maps a step to the parent it's waiting for (inverse index for O(1) cleanup)
Algorithm
Processing an update:
-
Timestamp check: If we've seen this step before and the incoming timestamp is older, discard the entire event.
-
Record state: Update timestamp and status for this step.
-
Parent assignment: This is the complex part. Create a
_assign_parenthelper that:- Clears any pending wait from previous assignments
- If the new parent equals the current parent, skip
- If parent is
None, detach from current parent - If parent equals step itself, log error and reject
- If parent doesn't exist yet, detach from current parent and register as waiting
- If parent exists, run cycle detection
- If no cycle, move the step and its entire subtree
-
Resolve waiting children: If this is a brand-new step, check if any steps were waiting for it. Attach each one (they also get cycle-checked).
Cycle detection:
Walk upward from the proposed parent through the effective_parent chain. If you encounter the step being moved, it means that step is already an ancestor of the target, so attaching would create a loop.
Building the tree:
Use an iterative traversal with a stack to avoid Python's recursion limit. Start from all roots, add them to the output dictionary, and push their children onto the stack.
Complexity
-
Time:
update: O(h) where h is tree height, for the ancestor walk. When a new parent arrives, attaching k waiting children costs O(k·h), but each child is attached at most once, so this is amortized.get_tree: O(N log N) if you sort children for deterministic output, O(N) without sorting.
-
Space: O(N + W) where N is the number of steps and W is pending parent references.
Implementation
from collections import defaultdict
class ProgressTracker:
def __init__(self):
self.timestamps = {}
self.statuses = {}
self.effective_parent = {}
self.children = defaultdict(set)
self.waiting_for = defaultdict(set) # missing_parent -> {waiting_steps}
self.pending_parent = {} # step -> missing_parent
def update(self, event: dict) -> None:
step = event["step_id"]
ts = event["timestamp"]
# Ignore stale events
if step in self.timestamps and ts < self.timestamps[step]:
return
is_new_step = step not in self.timestamps
self.timestamps[step] = ts
self.statuses[step] = event.get("status")
if is_new_step:
self.effective_parent[step] = None
# Process parent assignment
self._assign_parent(step, event.get("parent_id"))
# If this step just appeared, attach any children waiting for it
if is_new_step and step in self.waiting_for:
for child in list(self.waiting_for[step]):
self.waiting_for[step].discard(child)
if not self.waiting_for[step]:
del self.waiting_for[step]
self.pending_parent.pop(child, None)
self._assign_parent(child, step)
def get_tree(self) -> dict:
result = {}
roots = sorted(s for s, p in self.effective_parent.items() if p is None)
# Iterative traversal to avoid recursion limits
stack = [(root, result) for root in reversed(roots)]
while stack:
node, container = stack.pop()
node_dict = {}
container[node] = node_dict
# Process children in reverse so they appear sorted in output
for child in sorted(self.children[node], reverse=True):
stack.append((child, node_dict))
return result
def _assign_parent(self, step, new_parent):
# Clear any pending wait state
if step in self.pending_parent:
old_pending = self.pending_parent.pop(step)
self.waiting_for[old_pending].discard(step)
if not self.waiting_for[old_pending]:
del self.waiting_for[old_pending]
current = self.effective_parent[step]
# No change needed
if new_parent == current:
return
# Detach to become root
if new_parent is None:
self._detach(step)
return
# Self-reference: reject but continue
if new_parent == step:
return
# Parent doesn't exist yet: become orphan root
if new_parent not in self.timestamps:
self._detach(step)
self.waiting_for[new_parent].add(step)
self.pending_parent[step] = new_parent
return
# Cycle check: walk ancestors from proposed parent
if self._creates_cycle(step, new_parent):
return
# Valid assignment: detach and reattach
self._detach(step)
self.effective_parent[step] = new_parent
self.children[new_parent].add(step)
def _detach(self, step):
"""Remove step from its current parent's children."""
current_parent = self.effective_parent[step]
if current_parent is not None:
self.children[current_parent].discard(step)
if not self.children[current_parent]:
del self.children[current_parent]
self.effective_parent[step] = None
def _creates_cycle(self, step, proposed_parent):
"""Check if assigning step to proposed_parent would create a cycle."""
ancestor = proposed_parent
while ancestor is not None:
if ancestor == step:
return True
ancestor = self.effective_parent[ancestor]
return False
Common Mistakes
-
Applying partial updates from stale events: When an event is stale, ignore all fields including status and parent, not just the parent.
-
Not checking cycles when attaching waiting children: When a parent finally arrives, each waiting child must still be cycle-checked during attachment.
-
Using recursion for tree traversal: Deep hierarchies can exceed Python's recursion limit. Use an iterative approach with a stack.
-
Forgetting the inverse index: Without
pending_parent, clearing a step's wait state requires scanning all entries inwaiting_for, making updates O(N). -
Creating placeholder nodes: If a parent hasn't appeared, make the child a temporary root. Don't invent placeholder entries that pollute the output.