KatInterview

Determine Build Task Schedule

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsgraphtopological-sortbfs

Last updated

Find a valid topological sequence for tasks with prerequisite constraints or detect cyclic dependencies.

You are given a list of task names and a list of direct dependency constraints between tasks. Each dependency constraint is represented as a pair [A, B], which indicates that task A depends on task B (meaning task B must complete before task A can begin).

Determine a valid execution sequence for all tasks that honors all dependency constraints. If multiple valid execution sequences exist, any valid sequence is acceptable. If a valid schedule is impossible due to circular dependencies, return None.

Constraints

  • 1 <= len(pipelines) <= 1000
  • 0 <= len(dependencies) <= 5000
  • Task names are non-empty strings.
  • All task names listed in dependencies are guaranteed to exist in pipelines.
  • Input dependency lists may contain duplicate dependency pairs.

Examples

Example 1

Input: pipeline_execution_order(['P1', 'P2', 'P3'], [['P1', 'P2'], ['P3', 'P2']])

Output: ['P2', 'P1', 'P3']

Example 2

Input: pipeline_execution_order(['A', 'B', 'C', 'D'], [['B', 'A'], ['C', 'A'], ['D', 'B'], ['D', 'C']])

Output: ['A', 'B', 'C', 'D']

Example 3

Input: pipeline_execution_order(['build', 'test', 'deploy'], [['test', 'build'], ['deploy', 'test']])

Output: ['build', 'test', 'deploy']

Hints

Hint 1

Model the tasks as nodes in a directed graph where an edge points from a prerequisite to a dependent task.

Hint 2

Use topological sorting algorithms like Kahn's algorithm (BFS using in-degrees) or standard depth-first search (DFS).

Hint 3

If the processed output contains fewer tasks than the total list, a cycle exists.