Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Build the systems
EXPERIMENT 65 / 66

Make the order do useful work.

Calculate an earliest completion bound for a DAG with unlimited parallel workers.

BY NAVAN SAMI◷ 12 MIN READSTRETCHPROJECT

01 Model the idea

A valid topological order gives precedence but not a duration-aware completion estimate. This project computes each task’s earliest start as the maximum finish time of its prerequisites. With unlimited workers and no resource contention, the maximum task finish is the project’s earliest possible completion time. That is a precise model, not a promise about a real team with limited people or machines.

THE THING THAT MUST STAY TRUE

A ready task’s earliest start includes every completed prerequisite’s finish.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
VALIDATE ids and durations
PROCESS zero-indegree tasks
PROPAGATE maximum predecessor finish
REJECT incomplete processing as a cycle

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

build_planner.py
from collections import deque
def plan(tasks, prerequisites):
    if set(tasks) != set(prerequisites): raise ValueError("Every task needs a dependency list")
    if any(type(value) is not int or value < 0 for value in tasks.values()):
        raise ValueError("Nonnegative integer durations required")
    dependents = {task: [] for task in tasks}
    degree = {task: len(set(prerequisites[task])) for task in tasks}
    for task, required in prerequisites.items():
        for previous in set(required):
            if previous not in tasks: raise ValueError("Unknown prerequisite")
            dependents[previous].append(task)
    queue = deque(task for task in tasks if degree[task] == 0)
    start, finish, order = {task: 0 for task in tasks}, {}, []
    while queue:
        task = queue.popleft(); order.append(task)
        finish[task] = start[task] + tasks[task]
        for following in dependents[task]:
            start[following] = max(start[following], finish[task])
            degree[following] -= 1
            if degree[following] == 0: queue.append(following)
    if len(order) != len(tasks): raise ValueError("Dependency cycle")
    return order, finish, max(finish.values(), default=0)
tasks = {"design": 2, "build": 5, "test": 3, "docs": 2}
prerequisites = {"design": [], "build": ["design"], "test": ["build"], "docs": ["design"]}
order, finish, total = plan(tasks, prerequisites)
print(order)
print("Unlimited-worker completion:", total)
↳ EXPECTED OUTPUT
['design', 'build', 'docs', 'test']
Unlimited-worker completion: 10
  1. 1

    The indegree counts unmet prerequisite identities. Duplicate prerequisite names are normalised so they do not create contradictory counts.

  2. 2

    A dependent’s start takes the maximum finish across its prerequisites, not their sum, because those predecessors can run in parallel under this model.

  3. 3

    Reject cycles and unknown prerequisite ids before presenting a schedule. Add predecessor tracking if you want to display an actual critical path rather than only its length.

04 Count the cost

TIME

O(V + E) expected with hashed task ids

SPACE

O(V + E) state and dependency adjacency

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Test parallel independent tasks, a cycle, and an empty project.

Reveal one possible solution +
one_possible_solution.py
from collections import deque
def plan(tasks, prerequisites):
    if set(tasks) != set(prerequisites): raise ValueError("Every task needs a dependency list")
    if any(type(value) is not int or value < 0 for value in tasks.values()):
        raise ValueError("Nonnegative integer durations required")
    dependents = {task: [] for task in tasks}
    degree = {task: len(set(prerequisites[task])) for task in tasks}
    for task, required in prerequisites.items():
        for previous in set(required):
            if previous not in tasks: raise ValueError("Unknown prerequisite")
            dependents[previous].append(task)
    queue = deque(task for task in tasks if degree[task] == 0)
    start, finish, order = {task: 0 for task in tasks}, {}, []
    while queue:
        task = queue.popleft(); order.append(task)
        finish[task] = start[task] + tasks[task]
        for following in dependents[task]:
            start[following] = max(start[following], finish[task])
            degree[following] -= 1
            if degree[following] == 0: queue.append(following)
    if len(order) != len(tasks): raise ValueError("Dependency cycle")
    return order, finish, max(finish.values(), default=0)
assert plan({"A": 4, "B": 6}, {"A": [], "B": []})[2] == 6
assert plan({}, {})[2] == 0
try: plan({"A": 1, "B": 1}, {"A": ["B"], "B": ["A"]})
except ValueError: pass
else: raise AssertionError("Cycle accepted")
print("Planning assumptions verified")

Definition of done

  • □Validate task identities and nonnegative durations.
  • □Reject dependency cycles.
  • □Calculate finish times under an explicit unlimited-worker model.
  • □Return ten units for the example project.
  • □Test empty and parallel-only projects.

06 Check your reasoning

QUICK SIGNAL CHECK

Why take the maximum predecessor finish, not the sum?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.