Skip to content
mlmentorship

Release a dependency only when its unmet-requirement count reaches zero

Remove eligible prerequisite vertices, account for every outgoing edge, and distinguish blocked residual nodes from actual cycle members.

Published · 22 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Release a dependency only when its unmet-requirement count reaches zero

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonnegative course_count and pairs [course, prerequisite] using IDs from 0 through course_count - 1. Output. Return True if some order completes every course; otherwise return False. Rules. Each listed prerequisite must finish before its course can start. All courses count, including isolated ones. Repeated pairs are allowed, and inputs remain unchanged. Zero courses is feasible. A course requiring itself is not feasible. Example. Four courses with pairs [[1, 0], [2, 0], [3, 1], [3, 2]] return True. One possible order is [0, 1, 2, 3]. For two courses with pairs [[1, 0], [0, 1]], return False.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Complete a prerequisite, remove its outgoing obligations, and release a course only when none remain.

One finished prerequisite leaves course 3 waiting for the other

One completed parent still leaves the other prerequisite unmetCourse 3 requires courses 1 and 2. Its unmet count falls from two to one to zero, becoming ready only at zero.Each emitted parent removes one unmetprerequisite1222 unmet: course three remainsblocked.1211 unmet: course three remainsblocked.120Zero unmet: course three becomesready.
Read it this way: Course 3 requires courses 1 and 2. Its unmet count falls from two to one to zero, becoming ready only at zero. Is course three ready after only prerequisite one is emitted?
Full interview answer 22 min read

Determine whether every course can be completed while respecting all listed prerequisite requirements.

Problem

Input. A nonnegative course_count and pairs [course, prerequisite] using IDs from 0 through course_count - 1.

Output. Return True if some order completes every course; otherwise return False.

Rules. Each listed prerequisite must finish before its course can start. All courses count, including isolated ones. Repeated pairs are allowed, and inputs remain unchanged. Zero courses is feasible. A course requiring itself is not feasible.

Example. Four courses with pairs [[1, 0], [2, 0], [3, 1], [3, 2]] return True. One possible order is [0, 1, 2, 3]. For two courses with pairs [[1, 0], [0, 1]], return False.

Picture

The label counts unmet incoming requirements. Initially, only course 0 is ready:

Reference drawing

One finished prerequisite leaves course 3 waiting for the other

One completed parent still leaves the other prerequisite unmetCourse 3 requires courses 1 and 2. Its unmet count falls from two to one to zero, becoming ready only at zero.Each emitted parent removes one unmetprerequisite1222 unmet: course three remainsblocked.1211 unmet: course three remainsblocked.120Zero unmet: course three becomesready.
Derivation
One finished prerequisite does not make course 3 readyThe diamond graph has edges zero to one and two, and both one and two to three. Course three starts with two unmet prerequisites. Emitting one parent leaves one; only emitting both reduces the count to zero and makes three ready.0123Course 3 unmet requirements: 2 -> 1 -> 0Only after BOTH parents are emitted is 3 ready.
Course 3 has two incoming requirements. Its unmet count changes 2 -> 1 -> 0 as the parents finish. Ready is not the same as already completed.
Read it this way: Course 3 requires courses 1 and 2. Its unmet count falls from two to one to zero, becoming ready only at zero. Is course three ready after only prerequisite one is emitted?

Completing 0 releases 1 and 2. Completing 1 lowers course 3 from two requirements to one; it must still wait. Completing 2 lowers that count to zero and releases 3.

Indegree counts incoming requirements not yet released. After a course’s outgoing edges are processed, this equals incoming edges from unprocessed vertices. A ready course has no remaining prerequisite. Removing it deletes each outgoing requirement exactly once. Duplicate pairs remain consistent parallel edges: count and decrement every copy.

Problem trace

Remove obligations as each ready course completes

Input and goalCheck whether all courses can be completed.
Build the dependency graphThe prerequisite diamond starts with indegrees [0,1,1,2]. Only course 0 is ready.
0: ready1: needs 12: needs 13: needs 20123
Input adjacency matrix
from\to01230-0->10->2-1---1->32---2->33----
examplecourse_count = 4, prerequisites = [[1,0], [2,0], [3,1], [3,2]]edgeMeaningmatrix cell is prerequisite -> coursecompleted0
example
course_count = 4, prerequisites = [[1,0], [2,0], [3,1], [3,2]]
edge meaning
matrix cell is prerequisite -> course
completed
0

Recognize it
Directed prerequisite pairs ask whether every node can be placed after all requirements; failure to process every node means a directed cycle blocks the remainder.
Keep true
Every queued course has indegree zero in the remaining graph, completed counts dequeued courses, and each outgoing edge is removed exactly once when its prerequisite completes.
Reuse it
Repeatedly remove entities with no unmet requirements and decrement their dependents; the same mechanism orders builds, recipes, jobs, and dependency migrations, while leftovers certify a cycle.
The prerequisite diamond starts with indegrees [0,1,1,2]. Only course 0 is ready. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is an empty ready queue alone insufficient to return true?

Problem trace

An empty ready queue proves success only if every course was emitted

Worked example: an empty ready queue is not enough to prove successAn empty ready queue occurs after both a completed three-course chain and a blocked B-C cycle. Success additionally requires emitting every course.The ready queue can empty beforeevery course has emittedCompleted chain: all three emittedABCReady queue: emptyAll 3 courses emitted: successA emitted; B and C still wait on eachotherABCReady queue: emptyOnly 1 of 3 emitted: blocked by cycle
Read it this way: An empty ready queue occurs after both a completed three-course chain and a blocked B-C cycle. Success additionally requires emitting every course. When the ready queue is empty but B and C still wait on each other, have all three courses completed?
Reference drawing

Problem trace

An empty ready queue proves success only if every course was emitted

Worked example: an empty ready queue is not enough to prove successAn empty ready queue occurs after both a completed three-course chain and a blocked B-C cycle. Success additionally requires emitting every course.The ready queue can empty beforeevery course has emittedCompleted chain: all three emittedABCReady queue: emptyAll 3 courses emitted: successA emitted; B and C still wait on eachotherABCReady queue: emptyOnly 1 of 3 emitted: blocked by cycle
Execution trace
Input and goalCheck whether all courses can be completed.
Build the dependency graphThe prerequisite diamond starts with indegrees [0,1,1,2]. Only course 0 is ready.
0: ready1: needs 12: needs 13: needs 20123
Input adjacency matrix
from\to01230-0->10->2-1---1->32---2->33----
examplecourse_count = 4, prerequisites = [[1,0], [2,0], [3,1], [3,2]]edgeMeaningmatrix cell is prerequisite -> coursecompleted0
example
course_count = 4, prerequisites = [[1,0], [2,0], [3,1], [3,2]]
edge meaning
matrix cell is prerequisite -> course
completed
0

Recognize it
Directed prerequisite pairs ask whether every node can be placed after all requirements; failure to process every node means a directed cycle blocks the remainder.
Keep true
Every queued course has indegree zero in the remaining graph, completed counts dequeued courses, and each outgoing edge is removed exactly once when its prerequisite completes.
Reuse it
Repeatedly remove entities with no unmet requirements and decrement their dependents; the same mechanism orders builds, recipes, jobs, and dependency migrations, while leftovers certify a cycle.
The prerequisite diamond starts with indegrees [0,1,1,2]. Only course 0 is ready. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is an empty ready queue alone insufficient to return true?
Read it this way: An empty ready queue occurs after both a completed three-course chain and a blocked B-C cycle. Success additionally requires emitting every course. When the ready queue is empty but B and C still wait on each other, have all three courses completed?

If all four courses are removed, all can finish. If elimination stops early, every remaining vertex has an incoming requirement. Following predecessors in that finite residual graph must repeat a vertex, proving a directed cycle. Not every blocked vertex must itself lie on that cycle.

Code

from collections import deque

def can_finish(course_count: int, prerequisites: list[list[int]]) -> bool:
   graph = [[] for _ in range(course_count)]
   indegree = [0] * course_count

   for course, prerequisite in prerequisites:
      graph[prerequisite].append(course)
      indegree[course] += 1

   ready = deque(course for course in range(course_count) if indegree[course] == 0)
   completed = 0

   while ready:
      course = ready.popleft()
      completed += 1
      for next_course in graph[course]:
         indegree[next_course] -= 1
         if indegree[next_course] == 0:
            ready.append(next_course)

   return completed == course_count

Time and space are , including the graph and queue. Zero courses return True. Eligibility is not shortest-distance priority, resource availability or a general scheduling guarantee. Releasing course 3 after only course 1 would violate its second prerequisite.

Change to Parallel Rounds

New task: Group unit-duration courses under unlimited parallel capacity.

Picture and change: Freeze the ready count per round. Newly released courses belong to the next round, not the current one.

def course_layers(course_count, prerequisites):
   graph = [[] for _ in range(course_count)]
   indegree = [0] * course_count
   for course, prerequisite in prerequisites:
      graph[prerequisite].append(course)
      indegree[course] += 1
   ready = deque(course for course in range(course_count)
              if indegree[course] == 0)
   layers, completed = [], 0
   while ready:
      layer = []
      for _ in range(len(ready)):
         course = ready.popleft()
         layer.append(course)
         completed += 1
         for dependent in graph[course]:
            indegree[dependent] -= 1
            if indegree[dependent] == 0:
               ready.append(dependent)
      layers.append(layer)
   return layers if completed == course_count else None

Check: The diamond returns [[0],[1,2],[3]]. A cycle returns None; zero courses return []. Three rounds are optimal only under the stated duration and capacity assumptions.

Use when: Dependency depth, not resource-constrained scheduling, is requested.

Change to Blocked-Node Output

New task: Return every residual blocked vertex.

Picture and change: Run elimination, then inspect positive remaining counts. They identify blocked vertices, not an exact cycle witness.

def blocked_after_elimination(course_count, prerequisites):
   graph = [[] for _ in range(course_count)]
   indegree = [0] * course_count
   for course, prerequisite in prerequisites:
      graph[prerequisite].append(course)
      indegree[course] += 1
   ready = deque(course for course in range(course_count)
              if indegree[course] == 0)
   while ready:
      course = ready.popleft()
      for dependent in graph[course]:
         indegree[dependent] -= 1
         if indegree[dependent] == 0:
            ready.append(dependent)
   return [course for course in range(course_count)
         if indegree[course] > 0]

Check: With pairs [[1,0],[0,1],[2,1]] and four courses, return [0,1,2]. Course 3 completes; 0,1 form a cycle, while 2 is merely downstream. Both adaptations remain in time and space.

Use when: Residual obstruction coverage is sufficient.

Transfer Check

Why cannot undirected union-find replace this directed-cycle test?

Answer

Connectivity forgets prerequisite direction. The diamond has an undirected cycle but no directed cycle and remains feasible. Representative equality therefore answers a different question.