CodeArchon

mediumGraphsFacebookAmazonMicrosoft

Course Prerequisite Plan

A university registrar checks whether a student can finish every course given the prerequisite dependency graph.

There are n courses labeled 0..n-1 with prerequisite pairs [a, b] meaning you must take b before a. Return true if you can finish all courses.

Choose approach

0
1
2
3
queue
0
1/6
Narrationstep 1 of 6

Seed queue with zero-indegree nodes: [0].

1from collections import deque
2def canFinish(n, prereqs):
3 adj = [[] for _ in range(n)]; indeg = [0]*n
4 for a, b in prereqs:
5 adj[b].append(a); indeg[a] += 1
6 q = deque(i for i in range(n) if indeg[i] == 0)
7 done = 0
8 while q:
9 u = q.popleft(); done += 1
10 for v in adj[u]:
11 indeg[v] -= 1
12 if indeg[v] == 0: q.append(v)
13 return done == n
Variables
queueSize=1

How to think about it

  1. Zero-indegree node = can be taken now.
  2. Removing it reduces its successors' indegrees.
  3. Cycle manifests as leftover indegrees > 0.

Edge cases to catch in interview

  • No prereqs -> true.
  • Self-loop -> false.

Examples

Example 1false
{"n":2,"prereqs":[[1,0],[0,1]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed