Hierarchical Task Tracker: OO Domain Model & Service Layer
Data Structure DesignModel answerLast updated
Design and implement an object-oriented model for a nested task manager with status propagation, recursive deletion, and attribute-based filtering.
Hierarchical Task Tracker
Build the domain model and service layer for a nested task management tool — think of it like the checklist feature in a collaborative doc editor, where tasks can contain sub-tasks at any depth.
What you need to model
Task attributes
Each task has:
- a required
titleand an optionaldescription - a
priority:LOW,MEDIUM, orHIGH(defaultMEDIUM) - an optional
due_date - zero or more string
tags - a
status:PENDING,IN_PROGRESS, orCOMPLETED(starts asPENDING) - an optional reference to a parent task (making it a subtask)
Tasks can be nested arbitrarily deep. A task with no parent is a root task.
Status propagation rules
- Marking a task
COMPLETEDmust also mark every descendantCOMPLETED. - Marking a task
PENDINGorIN_PROGRESSmust move every ancestor that is currentlyCOMPLETEDtoIN_PROGRESS.
These two rules must never trigger each other in a loop.
Deletion
Deleting a task removes it and every descendant from the system. Any external ID referring to a deleted task should produce a clear error, not a silent no-op or a stale object.
Querying
Provide a way to search across all tasks with any combination of: status, a single tag, priority. Results should be sortable by due_date (tasks without a date sort last) or by priority (HIGH first). An unrecognised sort key should raise an error.
Interface to implement
from enum import Enum
from typing import List, Optional, Set
from datetime import datetime
class Priority(Enum):
LOW = 1
MEDIUM = 2
HIGH = 3
class Status(Enum):
PENDING = "PENDING"
IN_PROGRESS = "IN_PROGRESS"
COMPLETED = "COMPLETED"
class TodoListService:
def create_task(
self,
title: str,
description: str = "",
priority: Priority = Priority.MEDIUM,
due_date: Optional[datetime] = None,
tags: Optional[Set[str]] = None,
parent_id: Optional[str] = None,
) -> str:
"""Returns the generated ID of the new task."""
...
def update_status(self, task_id: str, new_status: Status) -> None:
"""Applies the status and propagates up or down as required."""
...
def delete_task(self, task_id: str) -> None:
"""Removes the task and all descendants."""
...
def query_tasks(
self,
status: Optional[Status] = None,
tag: Optional[str] = None,
priority: Optional[Priority] = None,
sort_by: Optional[str] = None, # "due_date" | "priority"
) -> List["Task"]:
...
Behaviour to verify
service = TodoListService()
epic_id = service.create_task("Ship v2", priority=Priority.HIGH)
task_id = service.create_task("Write changelog", parent_id=epic_id)
# Completing the parent cascades downward
service.update_status(epic_id, Status.COMPLETED)
assert service.get_task(task_id).status == Status.COMPLETED
# Reopening the child bubbles upward
service.update_status(task_id, Status.IN_PROGRESS)
assert service.get_task(epic_id).status == Status.IN_PROGRESS
Edge cases to address
- A client holds a subtask ID, then the parent is deleted. What happens?
- A new subtask is added under an already-
COMPLETEDparent. - Sorting results when some tasks have no
due_date. - Preventing cycles if task reparenting is supported.
- Deep trees that would overflow Python's default recursion limit.
Hints
Hint 1
The tree structure is a classic Composite: every node — leaf or subtree — exposes the same interface. Store nodes in a flat dict keyed by ID so any traversal can start in O(1), and keep parent pointers so you can walk upward without a separate reverse-index.
Hint 2
Split propagation into two non-overlapping routines: one walks strictly downward (iterative DFS), the other walks strictly upward (follow parent pointers). If they never call each other, there is no ping-pong loop where reopening a child re-completes it.
Hint 3
Model each filter as a small object with a matches(task) method (the Specification pattern). Compose them with AND logic inside query_tasks. Adding a new filter — due-date range, full-text search — then means adding a class, not modifying existing method signatures.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three distinct concerns; keeping them separate makes each one easy to reason about.
-
Tree structure — Composite pattern. Every
Tasknode holds a reference to its parent and a list of children. A flatdict[str, Task]in the service gives O(1) lookup by ID. Parent pointers let you walk upward cheaply; the children list lets you walk downward. -
Invariant enforcement — service layer.
TodoListServiceis the only place that mutates status or structure. Propagation is two strictly separated routines:_complete_subtree(task)— iterative DFS downward, sets every descendant toCOMPLETED._reopen_ancestors(task)— follows parent pointers upward, moves everyCOMPLETEDancestor toIN_PROGRESS.
Neither calls the other. This is what prevents the ping-pong loop.
-
Filtering — Specification pattern. Each filter is a small class with a
matches(task) -> boolmethod. They compose with&.query_taskstranslates its keyword arguments into specs and combines them, so adding a new filter is additive, not a modification of existing code.
All traversals use an explicit stack or a pointer loop rather than recursion, so deeply nested trees cannot overflow Python's ~1000-frame recursion limit.
Complexity
| Operation | Time | Space |
|---|---|---|
create_task | O(1), O(d) if parent is COMPLETED | O(1) |
update_status to COMPLETED | O(s) subtree size | O(s) stack |
update_status to other | O(d) depth | O(1) |
delete_task | O(s) | O(s) stack |
query_tasks | O(n) scan + O(k log k) sort | O(k) |
Edge cases
| Scenario | Correct behaviour |
|---|---|
Unknown task_id | Raise KeyError immediately |
Empty title | Raise ValueError |
| Stale ID after parent deletion | Raise KeyError; the node is removed from the index and its parent pointer is cleared |
New subtask under COMPLETED parent | The new PENDING task triggers _reopen_ancestors, moving the parent to IN_PROGRESS |
PENDING parent with all-COMPLETED children | Allowed; rules only propagate in the two stated directions |
due_date absent during sort | Sorts last (treat None as datetime.max) |
Invalid sort_by | Raise ValueError — silent ignoring hides bugs |
Caller mutates the tags set after creation | Defensively copy on creation |
Common mistakes
- Recursive propagation calling itself bidirectionally. Fixing a child calls
_reopen_ancestors, which marks the parentIN_PROGRESS, which accidentally triggers a downward completion again. The fix is strict directional separation. - Recursive tree traversal. Python's default stack is ~1000 frames. A task list with 2000 levels of nesting raises
RecursionError. Use an explicit stack. - Mutating the index while iterating it. In
delete_task, collect all IDs to remove first, then delete them. - Not clearing parent pointers on deletion. A client holding a stale
Taskobject can then traverse.parentback into the live tree and corrupt it.
Python implementation
from __future__ import annotations
import uuid
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Dict, Iterator, List, Optional, Set
# ── Enums ─────────────────────────────────────────────────────────────────────
class Priority(Enum):
LOW = 1
MEDIUM = 2
HIGH = 3
class Status(Enum):
PENDING = "PENDING"
IN_PROGRESS = "IN_PROGRESS"
COMPLETED = "COMPLETED"
# ── Domain entity ─────────────────────────────────────────────────────────────
@dataclass(eq=False)
class Task:
task_id: str
title: str
description: str = ""
priority: Priority = Priority.MEDIUM
due_date: Optional[datetime] = None
tags: Set[str] = field(default_factory=set)
status: Status = Status.PENDING
parent: Optional[Task] = field(default=None, repr=False)
children: List[Task] = field(default_factory=list, repr=False)
def iter_subtree(self) -> Iterator[Task]:
"""Iterative pre-order DFS over self and all descendants."""
stack = [self]
while stack:
node = stack.pop()
yield node
stack.extend(reversed(node.children))
def iter_ancestors(self) -> Iterator[Task]:
node = self.parent
while node is not None:
yield node
node = node.parent
# ── Specification pattern ─────────────────────────────────────────────────────
class Spec:
def matches(self, task: Task) -> bool:
raise NotImplementedError
def __and__(self, other: Spec) -> Spec:
return _AndSpec(self, other)
class _AndSpec(Spec):
def __init__(self, *specs: Spec):
self._specs = specs
def matches(self, task: Task) -> bool:
return all(s.matches(task) for s in self._specs)
class _AnySpec(Spec):
def matches(self, task: Task) -> bool:
return True
class _StatusSpec(Spec):
def __init__(self, status: Status):
self._status = status
def matches(self, task: Task) -> bool:
return task.status == self._status
class _TagSpec(Spec):
def __init__(self, tag: str):
self._tag = tag
def matches(self, task: Task) -> bool:
return self._tag in task.tags
class _PrioritySpec(Spec):
def __init__(self, priority: Priority):
self._priority = priority
def matches(self, task: Task) -> bool:
return task.priority == self._priority
# ── Sort keys ─────────────────────────────────────────────────────────────────
_SORT_KEYS = {
"due_date": lambda t: (t.due_date is None, t.due_date or datetime.max),
"priority": lambda t: -t.priority.value, # HIGH (3) → -3 sorts first
}
# ── Service ───────────────────────────────────────────────────────────────────
class TodoListService:
def __init__(self) -> None:
self._tasks: Dict[str, Task] = {}
# ── public API ────────────────────────────────────────────────────────────
def create_task(
self,
title: str,
description: str = "",
priority: Priority = Priority.MEDIUM,
due_date: Optional[datetime] = None,
tags: Optional[Set[str]] = None,
parent_id: Optional[str] = None,
) -> str:
if not title:
raise ValueError("title must not be empty")
parent = self._resolve(parent_id) if parent_id else None
task = Task(
task_id=str(uuid.uuid4()),
title=title,
description=description,
priority=priority,
due_date=due_date,
tags=set(tags) if tags else set(),
parent=parent,
)
self._tasks[task.task_id] = task
if parent is not None:
parent.children.append(task)
# A new pending child under a completed parent violates the invariant
self._reopen_ancestors(task)
return task.task_id
def get_task(self, task_id: str) -> Task:
return self._resolve(task_id)
def update_status(self, task_id: str, new_status: Status) -> None:
task = self._resolve(task_id)
if new_status == Status.COMPLETED:
self._complete_subtree(task)
else:
task.status = new_status
self._reopen_ancestors(task)
def delete_task(self, task_id: str) -> None:
task = self._resolve(task_id)
# Detach from parent before collecting IDs (avoids live-tree references)
if task.parent is not None:
task.parent.children.remove(task)
task.parent = None
# Collect all IDs first, then remove — never mutate the index mid-iteration
ids_to_remove = [node.task_id for node in task.iter_subtree()]
for tid in ids_to_remove:
node = self._tasks.pop(tid)
node.parent = None # sever stale object references into the live tree
def query_tasks(
self,
status: Optional[Status] = None,
tag: Optional[str] = None,
priority: Optional[Priority] = None,
sort_by: Optional[str] = None,
) -> List[Task]:
spec: Spec = _AnySpec()
if status is not None:
spec = spec & _StatusSpec(status)
if tag is not None:
spec = spec & _TagSpec(tag)
if priority is not None:
spec = spec & _PrioritySpec(priority)
results = [t for t in self._tasks.values() if spec.matches(t)]
if sort_by is not None:
if sort_by not in _SORT_KEYS:
raise ValueError(f"Unknown sort_by value: {sort_by!r}")
results.sort(key=_SORT_KEYS[sort_by])
return results
# ── private helpers ───────────────────────────────────────────────────────
def _resolve(self, task_id: str) -> Task:
try:
return self._tasks[task_id]
except KeyError:
raise KeyError(f"No task with id {task_id!r}") from None
def _complete_subtree(self, root: Task) -> None:
"""Walk downward only. Sets every node in the subtree to COMPLETED."""
for node in root.iter_subtree():
node.status = Status.COMPLETED
def _reopen_ancestors(self, task: Task) -> None:
"""Walk upward only. Any COMPLETED ancestor becomes IN_PROGRESS."""
for ancestor in task.iter_ancestors():
if ancestor.status == Status.COMPLETED:
ancestor.status = Status.IN_PROGRESS
# Keep walking: a higher ancestor may still be COMPLETED
Follow-up: scaling the query
A full scan over n tasks is fine for hundreds of items. At millions of tasks you would maintain secondary indexes — a dict[Status, set[str]] mapping status to task IDs, similarly for tags and priority. Each write operation keeps the indexes in sync. Queries then intersect small ID sets rather than scanning everything, bringing query time to O(k log k) where k is the result count.