Answer common graph, grid, and array tasks
MicrosoftSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to model a dependency system as a directed graph and identify if a valid order exists using cycle detection (Kahn's Algorithm or DFS).
Problem: Course Dependency Resolver
There are n courses labeled from 0 to n-1. You are given an array of dependencies where dependencies[i] = [a, b] indicates that you must take course b before course a.
Your task is to determine if it is possible to finish all courses. If it is possible, return the valid order (any valid topological sort); otherwise, return an empty list.
Function Signature
def find_order(num_courses: int, dependencies: list[list[int]]) -> list[int]:
Constraints
1 <= num_courses <= 20000 <= len(dependencies) <= 5000- The graph may contain disconnected components.
Examples
Example 1:
Input: num_courses = 2, dependencies = [[1, 0]]
Output: [0, 1]
Explanation: To take course 1, you must first take course 0.
Example 2:
Input: num_courses = 4, dependencies = [[1, 0], [2, 0], [3, 1], [3, 2]]
Output: [0, 1, 2, 3] (or [0, 2, 1, 3])
Example 3:
Input: num_courses = 2, dependencies = [[1, 0], [0, 1]]
Output: []
Explanation: There is a cycle (0 depends on 1, 1 depends on 0), so it is impossible.
Edge Cases
num_courseswith no dependencies.- Disconnected graph components.
- Self-loops in dependencies.
Hints
Hint 1
Represent the dependencies as an adjacency list where each course points to the courses that depend on it.
Hint 2
Track the 'in-degree' of each node, which represents the number of prerequisites that must be completed before the course can be taken.
Hint 3
Use a queue to process all courses with an in-degree of 0, effectively 'removing' them and decreasing the in-degree of their neighbors.
Follow-up questions
- How would you modify this algorithm if you also needed to track the total time taken to complete the curriculum, assuming each course has a specific credit weight?
- What is the time and space complexity of your solution in terms of V (vertices) and E (edges)?
- How would you identify all courses that are part of a circular dependency if the output is an empty list?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.