CodePark/ problems / Can You Finish Every Course?
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Graphs and topological sort

Can You Finish Every Course?

mediumabout 25 minutes in an interview

You need to take numCourses courses, labelled 0 up to numCourses - 1. Some courses need another course done first. A pair [a, b] in prerequisites says: finish course b, and then course a can start.

Can you get through every course? Return true or false.

  • numCourses is between 1 and 1,000. There are up to 2,000 pairs.
  • The same pair can show up more than once.
  • A course can name itself ([3, 3]). Such a course can never be taken.
  • A course that appears in no pair can be taken whenever you like.
Input: numCourses = 3, prerequisites = [[1, 0], [2, 1]] Output: trueTake 0, then 1, then 2.
Input: numCourses = 3, prerequisites = [[1, 0], [2, 1], [0, 2]] Output: false0 needs 2, 2 needs 1, and 1 needs 0. So no course can go first.