Course Schedule with Topological Sort

Quick Overview

Given prerequisites for courses, determine if all courses can be finished and return a valid order. Tests topological sorting and cycle detection in directed graphs.

Google
Coding & Algorithms
Software Engineer
Google
Software Engineer
Phone Screen
Coding & Algorithms
Medium

0


Given prerequisites for courses, determine if all courses can be finished and return a valid order. Tests topological sorting and cycle detection in directed graphs.

Google phone screens often use graph problems disguised as scheduling, and course prerequisites is a common framing. The interviewer checks that you model the input as a directed graph, detect cycles correctly, and produce a valid order in linear time.

What the Interviewer Expects
  • Model courses as nodes and prerequisites as directed edges
  • Use Kahn's algorithm (in-degrees and a queue) or DFS with three colors
  • Detect a cycle when fewer than all courses are output
  • Return a valid ordering, not just a boolean
  • State O(V + E) time and space
  • Handle courses with no prerequisites and disconnected components
Key Topics to Cover
Topological sort
Kahn's algorithm
Cycle detection
Directed graphs
BFS and DFS
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you find the minimum number of semesters if courses with met prerequisites run in parallel?
  • How would you report the actual cycle to the user?
  • How would you return the lexicographically smallest valid order?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

This problem can be solved using topological sorting on a directed graph. The courses represent vertices and the prerequisites represent directed edges. The goal is to determine if there exists a ...

Approach
  1. Graph Representation: Use an adjacency list to represent the directed graph where each course has a list of its prerequisites.
  2. In-degree Tracking: Calculate the in-degree (number of prer...

Submit Your Answer
Markdown supported