Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
When should the program return false?
Can you take a course without a prerequisite?
Do we need track completed courses?
What are the three course statuses?
HAPPY CASE
Input: numCourses = 4, prerequisites = [[0,1], [1,2], [2,3]]
Output: true
Explanation: In this case it is possible, just take 0 -> 1 -> 2 -> 3
Input: numCourses = 4, prerequisites = [[0,1], [2,1], [2,3], [3,0]]
Output: true
Explanation: In this case it is possible, just take 2 -> 3 -> 0 -> 1
EDGE CASE
Input: numCourses = 5, prerequisites = []
Output: true
Explanation: In this case, no courses have prereqs, so we can take them in any order
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For graph problems, some things we want to consider are:
v
Ā has not been visited, then mark it asĀ 0
. If nodeĀ v
Ā is being visited, then mark it asĀ 1
. If we find a vertex marked asĀ 1
Ā in DFS, then there is a ring. If nodeĀ v
Ā has been visited, then mark it asĀ +1
. If a vertex was marked asĀ 1
, then no ring containsĀ v
Ā or its successors.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Only return false when we encounter a cycle
**Approach #1**
- Build a graph out of the prereq-course pairs
- Every course is a node in the graph, and for a pair [a, b], add a directed edge from b to a, indicating that b depends on a
- We can represent this via an adjacency list
- Traverse the graph
- We have to start with a node that has 0 prereqs, which graphically would be a node with outdegree 0
- Once that node is fulfilled, we can remove that node from the graph to indicate that it has been taken
- Then, we can repeat to find the next class we are eligible to take
- If by the end we have taken all the classes, return true
- If we reach a point where there are no eligible classes to take, return false
**Approach #2:** Use an adjacency list
- Ad list would look like this: ad_list = { 0: [3], 1: [0, 2], 2: [], 3: [2] }
- First iteration, len(ad_list[2]) == 0, so we know 2 does not have any dependencies, so take course 2, and remove any nodes pointing to 2, and remove 2
- ad_list = { 0: [3], 1: [0], 3: [] }
- Second iteration, len(ad_list[3]) == 0, so we know 3 has no dependencies, so take course 3
- ad_list = { 0: [], 1: [0] }
- Third iteration, len(ad_list[0]) == 0, so take course 0
- ad_list = {1: []}
- Fourth iteration, take course 1
- ad_list is empty, so we have taken all courses
ā ļø Common Mistakes
Implement the code to solve the algorithm.
Approach #1
class Solution {
Boolean[] completedCourses;
public boolean canFinish(int numCourses, int[][] prerequisites) {
completedCourses = new Boolean[numCourses];
// build an adjacency list
List<Integer>[] adjList = (ArrayList<Integer>[]) new ArrayList<?>[numCourses];
for(int[] e : prerequisites){
if(adjList[e[1]] == null)
adjList[e[1]] = new ArrayList<>();
adjList[e[1]].add(e[0]);
}
for(int i=0; i < numCourses; i++){
if(isCycle(i, adjList, new boolean[numCourses]))
return false;
}
return true;
}
// check if there is a cycle
private boolean isCycle(int course, List<Integer>[] adjList, boolean[] visited){
if(visited[course])
return true;
if(completedCourses[course] != null){
return false;
}
completedCourses[course] = true;
visited[course] = true;
List<Integer> nextCourses = adjList[course];
if(nextCourses != null){
for(int nextCourse : nextCourses){
if(isCycle(nextCourse, adjList, visited))
return true;
}
}
visited[course] = false;
return false;
}
}
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# create adjacency list
ad_list = {i: set() for i in range(numCourses)}
for prereq, course in prerequisites:
// add prereq to adjacency list
ad_list[course].add(prereq)
// check if there is a cycle
while len(ad_list) > 0:
next_course = None
for course in ad_list:
if len(ad_list[course]) == 0:
next_course = course
break
if next_course == None:
return False
for course in ad_list:
ad_list[course].discard(next_course)
ad_list.pop(next_course)
return True
Approach #2: This approach creates a graph out of the prereq-course pairs, and attempts to topologically sort the graph into the eligibleCourses
array.
# Java Solution
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
for(int pre[] : prerequisites){
indegree[pre[0]]++;
}
// create queue
Queue<Integer> q = new LinkedList<Integer>();
for(int i=0;i<indegree.length;i++){
if(indegree[i] == 0)
q.add(i);
}
if(q.isEmpty())
return false;
while(!q.isEmpty()){
int course = q.poll();
for(int pre[]: prerequisites){
if(pre[1] == course){
indegree[pre[0]]--;
if(indegree[pre[0]] == 0)
q.add(pre[0]);
}
}
}
// if there are still some edges left, then there exist some cycles
// due to dependencies, we cannot remove the cyclic edges
for(int a: indegree){
if(a != 0)
return false;
}
return true;
}
}
# Python Code
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
ad_list = {i: set() for i in range(numCourses)}
degrees = [0] * numCourses
for prereq, course in prerequisites:
ad_list[prereq].add(course)
degrees[course] += 1
eligibleCourses = []
for course in range(numCourses):
if degrees[course] == 0:
eligibleCourses.append(course)
i = 0
while i < len(eligibleCourses):
next_course = eligibleCourses[i]
for course in ad_list[next_course]:
degrees[course] -= 1
if degrees[course] == 0:
eligibleCourses.append(course)
i += 1
return len(eligibleCourses) == numCourses
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Time Complexity: O(V^2)
Space Complexity: OV + E)