KatInterview

Can Every Task Be Scheduled Given Dependency Pairs?

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

Last updated

Tests modeling dependencies as a directed graph and detecting whether a cycle prevents a complete valid ordering, e.g. via indegree-based topological sorting.

Scheduling With Dependencies

A study plan has n modules, numbered 0 through n - 1. Certain modules depend on others being finished first. These dependencies are given as a list of pairs requirements, where each pair [x, y] means module y must be completed before module x can be started.

Write a function that decides whether it is possible to complete every one of the n modules while respecting all the dependencies. Return True if some order of completing the modules satisfies every pair, and False otherwise.

Notes on behavior:

  • A module with no dependencies can be done at any time.
  • A pair of the form [x, x] means a module depends on itself, so it can never be completed.
  • Modules that do not appear in any pair still count and can always be completed on their own.
  • The dependencies may form several unconnected groups; the answer is True only if all groups can be fully completed.

Constraints

  • 1 <= n <= 2000
  • 0 <= len(requirements) <= 5000
  • Each pair [x, y] satisfies 0 <= x, y < n.
  • All pairs in requirements are distinct.

Examples

Example 1

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

Output: True

Example 2

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

Output: False

Hints

Hint 1

Treat each module as a node and each pair [x, y] as a directed edge from y to x. The question becomes whether this directed graph contains a cycle.

Hint 2

Count, for every module, how many unfinished dependencies it has (its in-degree). Modules with zero can be completed right now; completing one lowers the count of the modules that depend on it.

Hint 3

Simulate this with a queue and count how many modules you complete. If the count reaches n, everything can be finished; if it falls short, the leftover modules are stuck behind a cycle.