KatInterview

Find Valid Completion Sequence for Dependent Tasks

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphsbfs

Last updated

Tests understanding of topological sorting, dependency graph modeling, and cycle detection in directed acyclic graphs.

You are given n tasks numbered from 0 to n-1. Some tasks have dependencies: you receive a list prerequisites where each pair [a, b] indicates that task b must finish before task a can begin.

Return any valid sequence in which all n tasks can be completed while respecting every dependency. If no such sequence exists because the dependencies form a cycle, return an empty list.

Constraints:

  • 0 ≤ n ≤ 10⁵
  • 0 ≤ prerequisites.length ≤ 10⁵
  • prerequisites[i].length == 2
  • 0 ≤ a, b < n
  • All pairs [a, b] represent valid dependency relationships
  • A task may depend on itself (which creates a cycle)
  • The same dependency pair may appear multiple times

Examples

Example 1

Input: find_task_sequence(4, [[1, 0], [2, 0], [3, 1], [3, 2]])

Output: [0, 1, 2, 3]

Example 2

Input: find_task_sequence(2, [[1, 0], [0, 1]])

Output: []

Example 3

Input: find_task_sequence(3, [])

Output: [0, 1, 2]

Hints

Hint 1

Model the problem as a directed graph where each dependency [a, b] represents an edge from b to a. A valid completion order exists only if the graph contains no cycles.

Hint 2

Consider tracking how many unfinished prerequisites each task has. A task becomes ready to execute once all of its prerequisites are complete.

Hint 3

Use a queue-based approach that processes tasks with zero remaining prerequisites, updating dependent tasks as you go. If you process fewer than n tasks, a cycle must exist.