This is a graph problem. Given is numCourses (graph vertices) and and edge list. Each edge consists of a courses to be taken and a prerequisite for it. [Ci,Pi] - here Ci is a course that requires you to complete the prerequisite Pi.
But in paradoxical situation like [[1,0],[0,1]] where a course is a prerequisite of another prerequisite represents a cycle. So, if there exists a cycle like this, you cannot complete all courses, so return False else return True.
There’s also another way to detect a cycle - it’s Topological Sort. A topo-sort is a sorting algorithm that is usually applied on dependency graphs - very much like this one where a course depends on another course as a pre-requisite.
A dependency graph is a Directed Acyclic Graph (DAG).
So, once we get out topological ordering and the number of nodes in our original graph vs this ordering is different - that means there’s a cycle somewhere.
Code:
Python (DFS)
Python (Topological Sort)
Java (DFS)
Big O Analysis
Runtime
The runtime complexity here is O(N) as since we would visit all nodes atleast once.
Memory
The memory usage is O(N) since we use a set.