Here is the interview question prompt, presented for reference.
Here's a classic challenge that comes up in real-life interviews surprisingly often. Interviewers like it as a way to assess your ability to find the right data structure
for a non-obvious and non-trivial use case.
The prompt is as follows: you're a university student currently trying to plan their schedule for the following semester. There is n number of courses that you'll need to take to stay on track for graduation.
Of the n courses, several have prerequisite courses that you'll need to take beforehand. This requirement is defined using an array with two elements. A prerequisite pair in the form [course, prerequisite]
such as [4, 3]
means that you need to take course 3
before course 4
.
n = 3
preReqs = [[1, 0], [2, 1]]
// You need to take course 0 before 1, and 1 before 2,
// but that is an appropriate order.
// Running areAllCoursesPossible(n, preReqs) would return true.
However, sometimes the prerequisite pairings are not possible-- this will prevent you from staying on track! As an example, if we add an additional prerequisite requirement that you need to finish 2
before 0
, it wouldn't work:
n = 3
preReqs = [[1, 0], [2, 1], [0, 2]]
// This is impossible because you can't finish 2 before 0,
// since you need to finish 1 before 2, and 0 before 1.
In the above, an order of 0 -> 1 -> 2
or 2 -> 1 -> 0
would not fulfill the requirements, so areAllCoursesPossible(n, preReqs)
would return false
.
Given n and a list of prerequisite pairs, can you write a method to determine if it is possible to take all the courses? Hint: what are the conditions under which a prerequisite setup is impossible?
100000
100000
0
O(V+E)
, where V
are the courses and E
are the prerequisitesO(V)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Course Prerequisites.