MediumDepth-First SearchBreadth-First SearchGraphTopological Sort

Course Schedule

LeetCode
1 approach, code in all languages

You are given an integer numCourses representing the number of courses labeled from 0 to numCourses - 1. You are also given a list prerequisites where each entry [a, b] means you must complete course b before you are allowed to take course a.

Decide whether it is possible to finish every course. Return true if a valid order of study exists, and false otherwise.

The answer is false exactly when the prerequisite relationships form a cycle, because a cycle would force a course to depend on itself either directly or indirectly.

Example 1

Input: numCourses = 2, prerequisites = [[1,0]]

Output: true

There are two courses. Course 1 depends on course 0, so the order 0 then 1 finishes everything.

Example 2

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]

Output: false

Course 1 needs course 0 and course 0 needs course 1. This circular dependency makes both impossible.

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= a_i, b_i < numCourses
  • All the pairs prerequisites[i] are unique.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now