Build a Display Order for Tasks with Dedup, Filtering and Subtasks
Trees & GraphsModel answerLast updated
Turn a flat batch of scheduler tasks into a display list: merge duplicates, hide finished work, order by priority, and keep each subtask right under its parent.
You are building the "what should I look at next" view of a task scheduler. You receive a flat batch of tasks and must return them in display order.
Each task has a unique id, a description, a due_date, a numeric priority, a completed flag, and an optional parent_id. When parent_id is set, the task is a subtask of the task with that id.
from dataclasses import dataclass
from datetime import date
from typing import Optional
@dataclass
class Task:
id: int
description: str
due_date: date
priority: int
completed: bool
parent_id: Optional[int] # None for a top-level task
def build_schedule(tasks: list[Task]) -> list[Task]:
...
The display list is produced by these steps, in this order:
- Merge duplicates. Two tasks are duplicates if they share the same
(description, due_date). - Remove tasks that are already completed.
- Sort what remains by a priority rule (your interviewer or product owner defines it, so ask).
- Put every subtask directly after its parent.
Part 1: Implement build_schedule.
Before coding, list the questions you would ask and state the answer you will assume for each. At minimum, think about:
- Which direction of
priorityis more urgent, and how are ties broken? - Which copy survives when duplicates differ (one completed, different priorities, different parents)? What happens to subtasks that pointed at a removed copy?
- What happens to a subtask whose parent was removed or never existed?
- Can subtasks be nested more than one level deep? Are siblings sorted by the same rule?
- Can
parent_idlinks form a loop, and is that an error? - Does the order of the steps ever change the result?
State the time complexity of your solution.
Part 2: Working with an AI coding assistant. Suppose the environment provides an AI assistant and you are expected to use it as you would at work. Describe what you would delegate to it, what you would decide yourself, and how you would verify what it produces.
Hints
Hint 1
Write down the policy decisions first (priority direction, tie-break, which duplicate survives, orphan and cycle behavior). Once they are fixed, the code is mostly mechanical.
Hint 2
Order matters: if a completed copy and a pending copy are duplicates, picking an arbitrary survivor before dropping completed tasks can make a pending task disappear. Decide the survivor rule deliberately, and build a map from every removed id to the surviving id so parent links can be redirected.
Hint 3
Sort once globally, then bucket tasks into `children[parent_id]` (or `roots`) in that sorted order so every sibling list is already ordered. Emit with an iterative depth-first walk from the roots, and if some kept task was never emitted, the input has a cycle.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Decisions to settle first
I would state these out loud (and confirm them) before writing code.
| Question | Decision I'd propose |
|---|---|
| Priority direction | Smaller number is more urgent. This is isolated in one key function so flipping it is a one-line change. |
| Tie-break | (priority, due_date, description, id), which makes output fully deterministic. |
| Surviving duplicate | Prefer a not-completed copy, then the lowest id. This way a pending task is never hidden behind a finished twin. |
| Subtasks of a removed duplicate | Re-point them to the survivor through an old_id -> surviving_id map. |
| Orphan (parent missing or dropped) | Promote to top level, because pending work should not silently vanish. Dropping the whole subtree is a reasonable alternative if the product wants it. |
| Depth and sibling order | Arbitrary depth, siblings use the same sort key. |
| Cycle (including a task that ends up as its own parent after remapping) | Raise ValueError. A cycle is corrupt data, and guessing hides the bug. |
On step order: it does matter. Deduplicating before dropping completed tasks only behaves well because of the survivor rule above. With a naive "keep the first seen" rule, a completed copy listed first would win and then be dropped, losing a still-pending twin. Filtering first would also change which parents exist for remapping. So I fix the order given in the prompt and make the survivor rule explicit.
Approach
- Deduplicate. Walk the tasks and keep a dict keyed by
(description, due_date). Replace the stored task if the new one has a smaller(completed, id). Then buildcanon[id] -> surviving idfor every input task. - Filter. Keep survivors that are not completed. Index them by id.
- Sort. Sort the kept tasks once with the priority key.
- Bucket. For each task in sorted order, compute its remapped parent id. If that parent is in the kept set, append the task to
children[parent], otherwise append it toroots. Because we iterate in sorted order, every list is already correctly ordered, so there is no per-level re-sorting. - Emit. Do an iterative pre-order DFS from the roots (an explicit stack avoids recursion limits on deep chains). Push children in reverse so the highest-priority child pops first.
- Cycle check. If the output length is smaller than the number of kept tasks, some tasks were unreachable from any root, which means they sit on or below a cycle.
Code
from collections import defaultdict
def build_schedule(tasks):
def sort_key(t):
return (t.priority, t.due_date, t.description, t.id)
# 1. Deduplicate: prefer pending, then lowest id.
best = {}
for t in tasks:
k = (t.description, t.due_date)
cur = best.get(k)
if cur is None or (t.completed, t.id) < (cur.completed, cur.id):
best[k] = t
canon = {t.id: best[(t.description, t.due_date)].id for t in tasks}
# 2. Drop completed survivors.
kept = [t for t in best.values() if not t.completed]
kept_ids = {t.id for t in kept}
# 3 + 4. Sort once, bucket by parent.
children = defaultdict(list)
roots = []
for t in sorted(kept, key=sort_key):
pid = canon.get(t.parent_id) if t.parent_id is not None else None
if pid == t.id:
raise ValueError(f"task {t.id} is its own parent")
if pid is not None and pid in kept_ids:
children[pid].append(t)
else:
roots.append(t) # top-level or orphan
# 5. Iterative pre-order DFS.
result = []
stack = list(reversed(roots))
while stack:
t = stack.pop()
result.append(t)
stack.extend(reversed(children[t.id]))
# 6. Anything unreachable is part of a cycle.
if len(result) != len(kept):
raise ValueError("cycle detected in parent_id links")
return result
A parent_id that is not in canon (a dangling reference) gives pid = None, so the task becomes a root, which matches the orphan rule.
Complexity
- Deduplication, filtering, bucketing and traversal are each O(n) with hashing.
- The single sort is O(n log n), and it dominates.
- Extra space is O(n).
Tests I would write
- Exact duplicates with different ids: only one survives, deterministically.
- Duplicate pair where one is completed: the pending one is shown.
- All copies completed: nothing shown, and their subtasks are promoted to top level.
- Subtask pointing at a removed duplicate: it appears under the survivor.
- Three or more levels of nesting, with siblings in priority order and a low-priority parent still ahead of its own high-priority child.
- A child with higher urgency than an unrelated root: it must still stay under its parent.
- Dangling
parent_id, completed parent with a pending child. - Two-node cycle, self-parent, and a subtree hanging off a cycle: each raises.
- Empty input, and ties on priority.
Common mistakes
- Sorting the whole list and then trying to "insert" children, which breaks at depth greater than one.
- Recursive DFS on a long chain, hitting the recursion limit.
- Keeping an arbitrary duplicate so that pending work is lost.
- Forgetting to remap parent ids from removed duplicates.
- Silently looping forever, or silently dropping tasks, on a cycle.
- Leaving the tie-break unspecified so output varies between runs.
Part 2: Using the AI assistant well
Delegate the mechanical pieces: the dataclass boilerplate, a first pass at the dict-based dedupe, the iterative DFS skeleton, and a draft table of test inputs.
Own the decisions myself: the policy table above, the survivor rule, the orphan and cycle behavior, and the complexity claim. I would write these as comments or a short spec first and give them to the assistant as constraints, instead of letting it infer defaults.
Verify by reading every generated line against the spec, not just running it. I would check the survivor comparison, the parent remapping, and the cycle check in particular, since assistants often skip those. I would then run the edge-case tests above, adding a few property-style checks (every kept task appears exactly once, no task precedes its parent, no completed task is present, output is identical across shuffled inputs). While working I would narrate why I accept or reject each suggestion, so the reviewer can see who is steering.