Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Can every course be finished?

Medium · Target 20 minutes · Graphs · Type asked atGoogleAmazonTwo Sigma

There are n courses, numbered 0 to n − 1. Each pair [a, b] in prereqs means course b must be taken before course a. Return true if it is possible to take every course, and false otherwise.

Examples

InputOutputWhy
n = 4, prereqs = [[1, 0], [2, 1], [3, 2]]trueA chain: take 0, 1, 2, 3 in order.
n = 3, prereqs = [[1, 0], [2, 1], [0, 2]]false0 before 1 before 2 before 0: a cycle, so none of them can start.
n = 5, prereqs = [[1, 0], [2, 0], [4, 3]]trueTwo separate groups, both without cycles.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ len(prereqs) ≤ 2 × 10⁵
  • 0 ≤ a, b < n; pairs may repeat

Hints

Hint 1

Draw an edge b → a for each pair. When can a course be taken right now?

Hint 2

A course can be taken when all its prerequisites are done: when its count of unfinished prerequisites (its in-degree) is zero.

Hint 3

Queue every course with in-degree 0. Taking one lowers the in-degree of the courses it unlocks; queue any that reach 0. Every course gets taken exactly when there is no cycle.

Where people lose marks

  • Reversing the edge direction. It does not change the yes/no answer, but it gives the order backwards if you are asked for it.
  • Recursive depth-first search for cycle detection with only two states. You need three (unvisited, on the current path, finished), or a chain looks like a cycle.
  • Recursion depth: a chain of 10⁵ courses overflows the stack in a recursive solution. Kahn's algorithm is iterative.
  • Forgetting courses that appear in no pair: they have in-degree 0 and must be counted as taken.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.