Skip to main content

Course Schedule II

Given numCourses and prerequisites[i] = [a, b] (take b before a) Return order to take all courses, or [] if impossible Example: numCourses=2, prerequisites=[[1,0]] => [0,1]

Given numCourses courses numbered from 0 to numCourses - 1 and an array of prerequisite pairs [a,b], return an integer array ordering all courses so that b appears before a for every pair. Each course number in a pair is within that range, and each course must appear exactly once in the result. Any valid ordering is accepted; return an empty array if the prerequisites contain a cycle and no ordering is possible.

BFS / DFSGraphsTopological Sort

Examples

You write

find_order(numCourses: int, prerequisites: List[List[int]])

  1. Example 1

    Input
    numCourses = 2, prerequisites = [[1,0]]
    returns
    [0,1]
  2. Example 2

    Input
    numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
    returns
    [0,1,2,3] or [0,2,1,3]

The pattern behind it

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Graphs

I reach for it when

  • The input is edges, prerequisites or connections.
  • You need cycles, an ordering or connected groups.

Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.

All 32 Graphs problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Find Course Order (Topological Sort)medium

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.