Problem Breakdown
Task Scheduler
Topological Sort
Published ·
medium
Try This Problem Yourself
Practice in the AI-enabled editor with real-time feedback
You're given a set of tasks. Each task has a string name, an integer duration, and a list of names it depends on. The Scheduler class already stores them, checks that dependency names are known and that no two tasks directly reference each other in a 2-cycle, and exposes two helpers worth remembering. (A cycle means a group of tasks where each depends on the next and the last loops back to the first, making them all impossible to schedule. The starter checks 2-cycles only because the scheduler's contract is that longer cycles are invalid upstream inputs, not something it needs to detect.) One helper returns every task that's currently ready to run given a set of completed tasks; call this the ready-task helper. The other returns the earliest moment a given task could start, given a map of when each of its dependencies finished; call this the earliest-start helper. You implement two methods on the Optimizer.
The first method returns a valid linear order (a topological sort of the dependency graph). Every dependency must appear before every task that depends on it. The second method returns a parallel schedule across a fixed number of workers, giving you a total makespan plus a timeline that says when each task runs.
The 5-task dependency DAG with durations on each node, and below it the 2-worker Gantt chart showing the 8-second schedule
The test suite has three graphs. The first two are small and well-behaved. The third is a critical-path graph where five tasks form a long chain that dominates the minimum possible makespan, plus four fat independent "scans" that look tempting to schedule early but have nothing to do with the chain.
Pattern: Topological Sort
Tasks with prerequisites form a dependency graph, and Kahn's algorithm peels off whatever has no remaining dependencies, one layer at a time. That's topological sort, the backbone of any scheduling or build-order problem.
Solution 1, topological sort with Kahn's algorithm
The order question has a standard answer in topological sort. In a dependency graph, a topological order is any sequence where every task comes after all of its dependencies. There are typically many valid orders; you just need one.
Complexity
What this solves, and what it doesn't
Solution 2, fixed-order worker assignment
Complexity
Where it breaks
Solution 3, event-driven simulation
Complexity
Why this wins on the critical-path test
Benchmarks
Takeaways
Purchase Premium to Keep Reading
Unlock this article and so much more with Hello Interview Premium
Reading Progress
On This Page