Coding problem
A study order that respects every prerequisite
The task
A training platform has courses numbered 0 to n − 1. A pair [a, b] means that course a must be finished before course b.
Complete StudyOrder(int n, int[][] before). Return an order that lists every course once and keeps every pair. Whenever several courses are free to take at the same moment, take the one with the smallest number first, so the answer is unique. If no order exists because the pairs form a loop, return an empty array.
Signature
public static int[] StudyOrder(int n, int[][] before)
Examples
- 4 courses, pairs
[[3, 1], [2, 1]]→[0, 2, 3, 1]. 0, 2 and 3 wait for nothing, so they go first, smallest first; 1 waits for 2 and 3. - 2 courses, pairs
[[0, 1], [1, 0]]→[]. Each course waits for the other.
Limits: Up to 400,000 courses and 400,000 pairs.
The tests check: one course, no pairs, a chain and a reversed chain, a course that must come before itself, a repeated pair, the smallest-number rule, a loop behind free courses, and a chain of 400,000 courses in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// A pair [a, b] means a comes before b; smallest free course first; [] when no order exists.
public static int[] StudyOrder(int n, int[][] before)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.