### Problem Statement

There are a total of `numCourses`

courses you have to take, labeled from `0`

to `numCourses-1`

.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: `[0,1]`

Given the total number of courses and a list of prerequisite **pairs**, is it possible for you to finish all courses?

**Example 1:**

Input:numCourses = 2, prerequisites = [[1,0]]Output:trueExplanation:There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

**Example 2:**

Input:numCourses = 2, prerequisites = [[1,0],[0,1]]Output:falseExplanation:There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

**Constraints:**

- The input prerequisites is a graph represented by
**a list of edges**, not adjacency matrices. Read more about how a graph is represented. - You may assume that there are no duplicate edges in the input prerequisites.
`1 <= numCourses <= 10^5`

### Video Tutorial

You can find the detailed video tutorial here### Thought Process

It is a classic dependency graph problem. We can translate this problem to direct if there is a cycle in a directed graph or not. A text book solution is Kahn's algorithm for topological sorting. We can have a simple way to represent the graph or use a more proper adjacency lists (a little bit overkill for this problem though)### Solutions

#### Use adjacency lists BFS

Time Complexity: O(V), since each vertex is visited only once during BFSSpace Complexity: O(V+E) since we use adjacency lists to represent a directed graph

#### Use simple hashmap BFS

Time Complexity: O(V), since each vertex is visited only once during BFS
Space Complexity: O(V) since we are using a hashmap

#### Use recursion DFS

Time Complexity: O(V), since each vertex is visited only once during BFS
Space Complexity: O(V) since we used a lookup hashmap for memorization purpose (not considering function stack space)

## No comments:

## Post a Comment

Thank your for your comment! Check out us at https://baozitraining.org/ if you need mock interviews!