Problem · Graph
Course Ordering with Concurrent Updates
Learn this problemProblem statement
Maintain prerequisites for numCourses courses numbered 0 through numCourses - 1. Process a finite operation history:
["ADD_PREREQUISITE", course, prerequisite]adds the edgeprerequisite -> course. Adding the same edge again has no effect and produces"null".["GET_ORDER"]produces the lexicographically smallest order that completes all courses, serialized without spaces, such as"[0,1,2]". If the graph contains a cycle, produce"[]".
Return one string for every operation. The history represents one legal linearization of concurrent calls: every update and query is atomic, and each query observes one complete committed graph state.
Function
courseOrderHistory(numCourses: int, operations: String[][]) → String[]Examples
Example 1
numCourses = 4operations = [["ADD_PREREQUISITE","1","0"],["ADD_PREREQUISITE","2","0"],["GET_ORDER"],["ADD_PREREQUISITE","0","1"],["GET_ORDER"]]return = ["null","null","[0,1,2,3]","null","[]"]The first query has two courses unlocked after 0, so the smaller label 1 comes first. The later reverse edge creates a cycle between 0 and 1.
Example 2
numCourses = 3operations = [["GET_ORDER"],["ADD_PREREQUISITE","2","1"],["ADD_PREREQUISITE","2","1"],["GET_ORDER"]]return = ["[0,1,2]","null","null","[0,1,2]"]The empty graph sorts by course label. The duplicate edge is ignored.
Constraints
1 <= numCourses <= 2000.1 <= operations.length <= 10000.- Each course and prerequisite is in
[0, numCourses - 1], and an update never uses the same course twice. - Calls are linearizable; the provided history is their complete atomic order.