KatInterview

Detect a Cycle in a Directed Course Prerequisite Graph

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphcycle-detection

Last updated

Tests whether you can model dependency constraints as a directed graph and use topological sort to detect cycles that make all tasks impossible to complete.

Problem

You are managing a collection of n jobs numbered 0 through n - 1. Some jobs have ordering requirements: a job cannot begin until another specific job has already been completed.

You are given an integer n and a list requirements, where each entry [a, b] means job a cannot start until job b is done.

Determine whether it is possible to complete every job. Return True if all jobs can be finished, or False if the constraints make it impossible.

Constraints

  • 1 <= n <= 2000
  • 0 <= len(requirements) <= 5000
  • requirements[i].length == 2
  • 0 <= requirements[i][0], requirements[i][1] < n
  • A job may appear in multiple requirement pairs.
  • requirements[i][0] != requirements[i][1] is not guaranteed (self-dependencies are possible).

Examples

Example 1

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

Output: True

Example 2

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

Output: False

Hints

Hint 1

Model the jobs as nodes in a directed graph where an edge from B to A means B must be done before A. The question reduces to: does this graph contain a cycle?

Hint 2

Use Kahn's algorithm: count how many unsatisfied prerequisites each job has (its in-degree). Jobs with in-degree 0 are ready to run immediately. Each time you complete a ready job, reduce the in-degree of every job that depended on it.

Hint 3

If the number of jobs you successfully process equals n, all jobs can be finished. If you get stuck before processing every job, a cycle exists and it is impossible.