Dsa
Heap
Medium
Course Schedule with Prerequisites
You are given a list of pairs representing course prerequisites. Each pair (a, b) states that course a must be taken before course b. Write a program to find whether you can finish all courses. If possible, return a list with the order of courses to take. If not, return 'Cannot complete courses'.
Input:
- The first line contains an integer n (number of courses).
- The subsequent lines contain the prerequisites as pairs of integers (total n-1 pairs).
Output:
- A list of courses in the order they should be taken or 'Cannot complete courses'.
Example:
Input:
4
2 1
3 1
3 2
Output:
[1, 2, 3, 4]
Key concepts
heapgraphstopological sorting
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now