Quick Overview

Determine whether every course can be completed from a list of prerequisite pairs. Use topological sorting to detect cycles in O(V + E) time, then discuss returning an order or reconstructing a cycle.

Determine Whether All Courses Can Be Completed

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Implement `can_finish(num_courses, prerequisites)`. Courses are numbered from `0` through `num_courses - 1`. Each pair `[course, prerequisite]` means the prerequisite must be completed before the course. Return `true` if all courses can be completed and `false` if the dependency graph contains a directed cycle. Courses with no dependencies may be taken immediately. Duplicate prerequisite pairs must not change the answer. Target `O(num_courses + p)` time and space, where `p` is the number of prerequisite pairs after deduplication. ```hint Remove courses with no remaining prerequisites Build indegrees and repeatedly process zero-indegree courses with a queue. ``` ```hint Count what the process removes If fewer than `num_courses` courses are processed, the unprocessed subgraph contains a cycle. ``` ### Discussion Extensions - How would you return one valid course order when the graph is acyclic? - How would a depth-first search with three colors reconstruct one concrete cycle when the graph is cyclic?

Quick Answer: Determine whether every course can be completed from a list of prerequisite pairs. Use topological sorting to detect cycles in O(V + E) time, then discuss returning an order or reconstructing a cycle.

Courses are numbered from 0 through num_courses - 1. Each pair [course, prerequisite] requires the prerequisite first. Return whether every course can be completed; duplicate pairs do not create extra dependencies.

Constraints

  • 1 <= num_courses <= 5,000.
  • 0 <= prerequisites.length <= 20,000.
  • Every pair contains valid course identifiers in [0, num_courses - 1].
  • Repeated prerequisite pairs have the same effect as one pair.

Examples

Input: (1, [])

Expected Output: True

Explanation: One independent course is immediately completable.

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

Expected Output: True

Explanation: A single prerequisite chain is acyclic.

Hints

  1. Track how many unmet prerequisites remain for each course and begin with courses whose count is zero.
  2. If the process stops before visiting every course, the unvisited portion contains a directed cycle.

Loading coding console...