← Questions

Course schedule: can every course be finished?

0
MetaCodingLast asked Dec 2025

A coding interview question asked in Meta's technical phone screen, last asked Dec 2025. It tests graphs, topological sort and cycle detection.

There are n courses labeled 0..n-1 and a list of prerequisite pairs; [a, b] means course b must be finished before course a. Return whether it is possible to finish every course, which is the same as asking whether the prerequisite graph has no cycle. You may be asked to talk the solution through and walk examples by hand rather than run it, so explain the approach and the test cases clearly.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • can_finish(n: int, prerequisites: list[list[int]]) -> bool.

Example

n = 2, prerequisites = [[1, 0]]                    ->  True    # take 0, then 1
n = 2, prerequisites = [[1, 0], [0, 1]]            ->  False   # 0 and 1 need each other
n = 4, prerequisites = [[1, 0], [2, 1], [3, 2]]    ->  True    # a chain
n = 3, prerequisites = [[1, 0], [2, 1], [0, 2]]    ->  False   # a 3-cycle

Constraints

  • 1 <= n <= 10^5; 0 <= len(prerequisites) <= 2 * 10^5.
  • Pairs may repeat; a pair [a, a] is a self-loop.

Clarifying questions

  • Which way does a pair point: does [a, b] mean b before a?
  • Can pairs repeat, or can a course list itself as a prerequisite?
  • Do I need an actual order of courses, or only yes or no?

What a strong answer covers

  • Building an adjacency list from prerequisite to dependent course.
  • Kahn's algorithm: compute in-degrees, start from every course with in-degree 0, remove edges as courses are taken; all courses can be finished exactly when every course gets taken.
  • Or DFS with three colours (unvisited, in progress, done); finding an in-progress node again means a cycle. Iterative, or with care about recursion depth for 10^5 nodes.
  • O(n + E) time and space.
  • Tests: no prerequisites, a self-loop, duplicate pairs, a long chain, a cycle in one component while others are fine.

Follow-ups

  • Return one valid order of all courses, or an empty list if none exists.
  • Return the courses that are part of some cycle.
  • Each semester you may take any number of available courses. What is the fewest number of semesters?

Where it's asked

  • Meta · Technical phone screen · Last asked Dec 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

graphs · topological sort · cycle detection

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding