Problem Statement:
There are a total of numCourses courses you have to take, labeled from 0 to numCourses — 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Input Format:
Integer and array depicting course to be taken and pre-requiste respectively
Output Format:
Boolean
Sample Input 1:
numCourses = 2, prerequisites = [[1,0]]
Sample Output 1:
True
Sample Input 2:
numCourses = 2, prerequisites = [[1,0],[0,1]]
Sample Output 2:
False
Constraint:
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCourses
Approach:
- Each element present in the prerequisite is treated as a node of a graph, as prerequisites[0] is dependent on prerequistes[1], a edge is directed from the latter to the former.
- But in case if any two elements direct each other, a cycle is formed and we will not be able to chose the subject and complete it.
- So if we find a cycle in the graph, our work is done.
Code:
Thanks for Reading
Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.
Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.