Lexicographically Smallest Topological Task Order (Kahn + Heap)

Difficulty: Hard · Unit 5: OOP, Iterators & Complexity · Featured in: Tough Challenge

You have V tasks labeled `0` to `V - 1` and E prerequisite pairs `u v` (meaning task `u` must finish before task `v`). Find a valid execution order of all tasks; whenever multiple tasks are ready simultaneously, always run the smallest numbered task first. If a dependency cycle prevents finishing all tasks, print `CYCLE`.

Input & Output Format

Input: Line 1: two integers V and E. Next E lines: two integers `u v`.

Output: Print V space-separated task IDs, or `CYCLE`.

Sample 1

4 3
2 0
2 1
1 3
2 0 1 3

Initially only task 2 has in-degree 0; after 2 finishes, both 0 and 1 become ready, so 0 runs before 1.

Free forever — sign in with email at poorvithmp.com to unlock the dry run, verified Python 3 solution, edge-case traps, and downloads.

Back to Python Notes Hub