Decide Whether Every Course Can Be Completed Given Prerequisite Pairs
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Given a number of courses and a list of prerequisite pairs, decide whether every course can be completed in some order. It tests modeling dependencies between tasks and reasoning about ordering on large inputs, including repeated pairs and courses that list themselves as a prerequisite.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- 1 <= num_courses <= 10^5
- 0 <= len(prerequisites) <= 2 * 10^5
- Every element of prerequisites is a pair [a, b] with 0 <= a <= num_courses - 1 and 0 <= b <= num_courses - 1
- A pair may repeat, and a pair may have a equal to b
- Every value fits in a signed 32-bit integer; no value can exceed 2^31 - 1
Examples
Input: (2, [[1, 0]])
Expected Output: True
Explanation: Source Example 1: take course 0, then course 1.
Input: (2, [[1, 0], [0, 1]])
Expected Output: False
Explanation: Source Example 2: the two courses require each other, a 2-cycle.
Hints
- Picture each course as a node and each pair [a, b] as a directed link from course b to course a.
- Ask what shape among the links would leave a group of courses each waiting, directly or through others, on another member of the same group. A pair [a, a] is the smallest such group.
- With up to 10^5 courses and 2 * 10^5 pairs, aim for time linear in their total, and keep in mind that a chain of prerequisites can be as long as the number of courses.