Prepin
Log in

Find a method to complete n college courses sequentially, from course 0 to n-1. Be aware that certain courses may have multiple prerequisites. Present any valid sequence or return [-1] if a solution is not feasible.

Approach / Explanation

This inquiry pertains to a problem category known as topological sorting in graph theory. The primary objective is to arrange a collection of vertices within a directed acyclic graph (DAG). In this scenario, the vertices represent college courses (numbered from 0 to n-1), and a directed edge from course A to course B indicates that course A must be completed before course B. Courses may have several prerequisites, allowing a single course to possess multiple incoming edges. The inquiry requests a method to produce a course sequence that meets all prerequisite requirements, or to return [-1] if it's unfeasible to complete all courses due to circular prerequisite dependencies (which contradicts the DAG condition). This problem can be tackled using either Depth First Search (DFS) or Breadth First Search (BFS): Construct a graph from the input, where nodes symbolize the courses and edges denote the prerequisite relationships. Employ DFS or BFS to navigate the graph: In the case of DFS, ensure that cycles are detected and cease further traversal if a cycle is encountered. For BFS, initiate with nodes that lack prerequisites. After processing a node, include it in the result and reduce the prerequisite count for its dependent nodes. If all courses are accounted for during the traversal (indicating no cycles were found), return the order; otherwise, return [-1].

Suggested Answer

This is a method utilizing BFS (commonly referred to as Kahn's algorithm) implemented in Python: from collections import deque , defaultdict def findOrder ( numCourses , prerequisites ) : graph = defaultdict ( list ) indegrees = defaultdict ( int ) for u , v in prerequisites : graph [ v ] . append ( u ) indegrees [ u ] += 1 dq = deque ( [ u for u in range ( numCourses ) if indegrees [ u ] == 0 ] ) result = [ ] while dq : v = dq . popleft ( ) result . append ( v ) for u in graph [ v ] : indegrees [ u ] -= 1 if indegrees [ u ] == 0 : dq . append ( u ) return result if len ( result ) == numCourses else [ - 1 ]

Alternative Answer

A possible implementation of DFS in Python is outlined below: from collections import defaultdict def findOrder ( numCourses , prerequisites ) : graph = defaultdict ( list ) for u , v in prerequisites : graph [ v ] . append ( u ) visited = [ 0 for _ in range ( numCourses ) ] stack = [ ] for course in range ( numCourses ) : if not dfs ( course , graph , visited , stack ) : return [ - 1 ] return stack [ : : - 1 ] def dfs ( course , graph , visited , stack ) : if visited [ course ] == - 1 : return False if visited [ course ] == 1 : return True visited [ course ] = - 1 for pre in graph [ course ] : if not dfs ( pre , graph , visited , stack ) : return False visited [ course ] = 1 stack . append ( course ) return True In this implementation of DFS, a course is designated as -1 while the DFS is being conducted from that course, and it is labeled as 1 once the DFS from that course is complete. If we encounter a course marked as -1 at any point during the DFS, it indicates that a cycle exists in the graph, leading us to return False . Conversely, if no cycles are found, we mark the node as completely processed ( 1 ) and append it to our course schedule (stack).

Question Details

Difficulty & Category

Medium
data structures

Companies

Amazon

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.