Coding questions · Uber
Check feasibility of AI course schedule
This question evaluates competency in analyzing directed graphs and dependency resolution, focusing on cycle detection and the feasibility of ordering prerequisites for course completion.
You are designing a learning path for n AI-related courses, labeled from 0 to n - 1.
Some courses have prerequisites. For example, to take course b, you may first need to finish course a. This can be represented as a directed edge a -> b.
You are given:
- An integer
n, the number of courses. - A list
prerequisitesof pairs[a, b], where each pair means: to take courseb, you must first complete coursea.
You need to determine whether it is possible to finish all courses.
Formally, model the courses as a directed graph:
- Each course is a node.
- Each prerequisite pair
[a, b]is a directed edge fromatob.
If the graph contains a cycle (e.g., 0 -> 1 -> 2 -> 0), then there is no way to complete all courses because each course in the cycle depends on another in the cycle.
Task
Write an algorithm that:
- Returns
trueif it is possible to complete allncourses given the prerequisites. - Returns
falseif it is not possible (i.e., if there is at least one cycle in the prerequisite graph).
Constraints (typical interview constraints; you may assume something like):
1 <= n <= 10^5.0 <= prerequisites.length <= 10^5.0 <= a, b < nfor every pair[a, b].
Your algorithm should run in O(n + m) time, where m = prerequisites.length, and use O(n + m) extra space.
You may use any standard graph traversal technique (e.g., DFS or BFS/topological sort).
Course Schedule Feasibility
Return true if all courses can be completed, false if prerequisites contain a cycle.
Examples
Example 1
Input: (2, [[0,1]])
Output: True
Explanation: Acyclic.
Example 2
Input: (2, [[0,1],[1,0]])
Output: False
Explanation: Cycle.
Hints
- Use deterministic tie-breaking for prompts with multiple valid outputs.
- For design-style APIs, simulate operations with explicit inputs.