KatInterview

Can Every Module in a Study Plan Be Finished?

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsgraphtopological-sortcycle-detection

Last updated

Decide whether a set of ordering rules between numbered modules contains a circular dependency, by detecting a cycle in a directed graph.

Finishing a Study Plan

A school offers a number of modules, numbered from 0 to module_count - 1. Some modules must be completed before others can be started. These rules are given as pairs [first, then], which means that module first has to be finished before module then can be taken.

A study plan is feasible if there is some order in which every module can be taken so that all the rules are respected. A plan is not feasible when the rules form a loop, for example, module 0 must come before 1, 1 before 2, and 2 before 0. A rule that makes a module depend on itself, such as [3, 3], is also a loop.

Write a function that returns True if all modules can be completed while obeying every rule, and False otherwise.

Input

  • module_count: the total number of modules, labeled 0 through module_count - 1.
  • rules: a list of pairs [first, then], each pair holding two module labels.

Output

Return a boolean: True if the plan is feasible, False if it contains a circular dependency.

Notes

  • If there are no rules, the plan is feasible.
  • The modules may form several unrelated groups. A loop in any one group makes the whole plan infeasible.

Constraints

  • 1 <= module_count <= 2000
  • 0 <= len(rules) <= 5000
  • Every pair in rules is distinct.
  • Every label in a pair is between 0 and module_count - 1.

Examples

Example 1

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

Output: True

Example 2

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

Output: False

Hints

Hint 1

Treat each module as a node and each rule [first, then] as a directed edge from first to then. The question becomes whether this directed graph has a cycle.

Hint 2

A module can be taken right away if it has no unmet requirements. Count the incoming edges of every node and start with the ones whose count is zero.

Hint 3

Each time you take a module, lower the count of every module that depends on it, and make any module whose count reaches zero available. If the number of modules you managed to take is less than module_count, a cycle blocked the rest.