All Tasks Scheduling Orders
Problem Statement
There are n tasks, numbered 0 to n − 1. Some tasks must be done before others. You get a list of pairs [a, b], which means task a must be done before task b.
Return every order in which all the tasks can be done, so that every pair is respected. The order of the orders in your answer does not matter.
If the pairs contradict each other (for example, a cycle), no order works, so return an empty list.
n: the number of tasks. prereqs: a list of pairs [a, b] meaning a must be done before b.
A list of orders. Each order is a list with all n task numbers, each once.
0 must come before 1. Task 2 has no rule, so it can go in any of the three places that keep 0 before 1.
0, then 1, then 2 is the only chain. There is one order.
0 before 1 and 1 before 0 cannot both hold, so no order exists.
- • Every value in a pair is between 0 and n − 1.
- • A pair can repeat, and a pair may be empty (no prerequisites at all).
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Build all n! orders; keep each one where every pair has its first task before its second
Kahn's free tasks as branches; place, recurse, then undo; keep every complete order
An order of all the tasks is a permutation of 0..n − 1. Generate every permutation. For each one, check that every pair [a, b] has a before b. Keep the permutations that pass.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.