{"id":"parallel-courses","title":"Parallel Courses","difficulty":"medium","patterns":["topological-sort"],"primaryConcept":"graph-toposort-feasibility","concepts":["graph-toposort-feasibility"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft","DoorDash"],"category":"trees-graphs","compareMode":"exact","executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"graph-edges","primaryParam":"relations","sizeMetric":"nodes-plus-edges","constraints":["dag","1-indexed"],"secondaryParams":{"n":{"strategy":"scale-with-primary"}}},"description":"You are given `n` courses labeled from `1` to `n` and an array `relations` where `relations[i] = [prevCourse, nextCourse]` means `prevCourse` must be completed before `nextCourse`.\n\nIn one semester, you may take any number of courses as long as all prerequisites for those courses have already been completed.\n\nReturn the minimum number of semesters needed to complete all courses. If it is impossible to complete every course because of a cycle, return `-1`.","examples":[{"input":"n = 3, relations = [[1, 3], [2, 3]]","output":"2","explanation":"Take courses 1 and 2 in semester 1, then course 3 in semester 2."},{"input":"n = 3, relations = [[1, 2], [2, 3], [3, 1]]","output":"-1","explanation":"The prerequisites form a cycle, so no course in the cycle can be completed."},{"input":"n = 1, relations = []","output":"1","explanation":"The only course has no prerequisites, so it can be taken in the first semester."}],"constraints":[{"id":"1-n-5000","text":"1 <= n <= 5000","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":5000}},{"id":"0-len-relations-5000","text":"0 <= len(relations) <= 5000","check":{"kind":"sizeRange","target":"relations","measure":"arrayLength","min":0,"max":5000}},{"id":"relations-i-length-2","text":"len(relations[i]) == 2","check":{"kind":"shape","target":"relations","shape":"tupleArray","tupleLength":2}},{"id":"1-prevcourse-nextcourse-n","text":"1 <= prevCourse, nextCourse <= n","check":[{"kind":"valueRange","target":"relations","selector":"tupleItemsAtIndex","index":0,"min":1,"max":{"valueOfInput":"n"}},{"kind":"valueRange","target":"relations","selector":"tupleItemsAtIndex","index":1,"min":1,"max":{"valueOfInput":"n"}}]},{"id":"prevcourse-nextcourse","text":"prevCourse != nextCourse","check":{"kind":"compare","target":"relations","left":{"field":0},"op":"!=","right":{"field":1}}},{"id":"all-prerequisite-pairs-are-unique","text":"All prerequisite pairs are unique","check":{"kind":"uniqueness","target":"relations","selector":"edges"}}],"starterCode":"class Solution:\n    def minimumSemesters(self, n: int, relations: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"minimumSemesters","testCases":[{"id":"1","input":{"n":3,"relations":[[1,3],[2,3]]},"expected":2,"description":"Two independent prerequisites unlock the final course."},{"id":"2","input":{"n":3,"relations":[[1,2],[2,3],[3,1]]},"expected":-1,"description":"A directed cycle prevents completion."},{"id":"3","input":{"n":1,"relations":[]},"expected":1,"description":"Single course with no prerequisites."},{"id":"4","input":{"n":4,"relations":[[1,2],[2,3],[3,4]]},"expected":4,"description":"A chain of prerequisites needs one course per semester."},{"id":"5","input":{"n":5,"relations":[[1,5],[2,5],[3,5],[3,4],[4,5]]},"expected":3,"description":"Several courses can be taken in parallel before a final dependent course."},{"id":"6","input":{"n":4,"relations":[[1,2],[1,3],[2,4],[3,4]]},"expected":3,"description":"A diamond dependency graph completes in three semesters."},{"id":"7","input":{"n":5,"relations":[[1,2],[2,3],[3,4],[4,2]]},"expected":-1,"description":"An independent course does not rescue a cycle in another component."},{"id":"h1","input":{"n":4,"relations":[]},"expected":1,"description":"With no prerequisites, every course fits in one semester."},{"id":"h2","input":{"n":6,"relations":[[1,4],[2,4],[3,5],[4,6],[5,6]]},"expected":3,"description":"Parallel prerequisite chains converge at the end."},{"id":"h3","input":{"n":5,"relations":[[1,2],[1,3],[2,4],[3,4]]},"expected":3,"description":"A diamond dependency graph still needs three semesters."},{"id":"topup-two-semester-wide-frontier","input":{"n":5,"relations":[[1,4],[2,4],[3,5]]},"expected":2,"description":"Several independent courses can be taken in the same semester."},{"id":"topup-cycle-impossible","input":{"n":4,"relations":[[1,2],[2,1],[3,4]]},"expected":-1,"description":"A prerequisite cycle makes completion impossible."}],"hints":[{"level":1,"content":"Courses with zero prerequisites can be taken immediately. What happens to their neighbors after a semester finishes?","revealPattern":false},{"level":2,"content":"Track each course's indegree. Each semester processes the current queue of zero-indegree courses as one layer.","revealPattern":true},{"level":3,"content":"Use Kahn's topological sort: build graph and indegree, queue all zero-indegree courses, process the queue level by level, and `return -1` if not all courses are completed.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should reuse course readiness across semesters?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"repeat-scan","name":"Repeated Prerequisite Scans","summary":"Each semester, scan every unfinished course and check whether all prerequisites are done.","decisionReason":"Repeated scans revisit every relation for each semester wave, while Kahn layers touch each course and edge only once.","complexity":{"time":"O(n * (n + e))","space":"O(n + e)"},"tradeoffs":["Runs in O(n * (n + e)) time and uses O(n + e) space."],"isOptimal":false,"steps":["Keep a completed set","Scan every course each semester","Take courses whose prerequisites are all completed","Repeat until no progress is possible"]},{"id":"kahn-layers","name":"Kahn's Topological Sort by Layers","summary":"Use indegrees and a queue of currently available courses. One queue layer equals one semester.","decisionReason":"Indegree counts how many prerequisite courses still block each course. Processing the current queue length as one semester takes every currently available course together, then unlocks the next semester's frontier.","complexity":{"time":"O(n + e)","space":"O(n + e)"},"tradeoffs":["Runs in O(n + e) time and uses O(n + e) space."],"isOptimal":true,"steps":["Build adjacency lists and indegree counts","Queue every course with indegree 0","Process the current queue length as one semester","Decrease neighbors' indegrees and enqueue newly available courses"]}]},"codingCheckpoints":[{"id":"build-graph","title":"Create adjacency lists","description":"Allocate an adjacency list for every course label.","commonMistakes":["Allocating only n slots for 1-indexed courses","Using one shared list for every course"],"hint":"Use n + 1 slots so course labels can be used directly as indexes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_adjacency","scope":"build-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Create a directed adjacency structure that can store outgoing unlocked-course edges.","doneWhen":"This step is done when every course label has a bucket for outgoing neighbors before relations are scanned.","shouldFailWhen":"This step should fail if no adjacency state exists or if all courses accidentally share the same neighbor list.","roles":["course graph","outgoing edges","course label"],"mustProve":["The graph state is initialized before prerequisite relations are processed.","The graph has enough slots or keys for every course label."],"mustNotAccept":["Trying to derive neighbors by rescanning relations later.","Using a scalar where adjacency lists are required."],"equivalentVariants":["Use a list of lists indexed by course label.","Use a map from course to a fresh neighbor list."],"proofSnippets":[{"id":"py-create-course-adjacency","language":"python","code":"def minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]"}]}},{"id":"calculate-indegree","title":"Create indegree counts","description":"Allocate an indegree count for every course.","commonMistakes":["Counting outgoing edges instead of incoming prerequisites","Forgetting isolated courses"],"hint":"Indegree stores how many prerequisites still block each course.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Create the counter state used to decide when a course becomes available.","doneWhen":"This step is done when every course has an initial zero prerequisite count before relations are scanned.","shouldFailWhen":"This step should fail if the solution has no counter state or initializes counts only for courses that appear as destinations.","roles":["indegree","prerequisite count","course label"],"mustProve":["The indegree state is initialized for the course domain.","The counts start at zero before relation population."],"mustNotAccept":["Using the adjacency list length as a substitute for incoming prerequisite count.","Skipping courses with no relation entries."],"equivalentVariants":["Use a zero-filled array of length n + 1.","Use a map with zero default values for course labels."],"proofSnippets":[{"id":"py-create-course-indegree","language":"python","code":"def minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)"}]}},{"id":"populate-graph","title":"Populate graph and indegree","description":"For each prerequisite pair, add the outgoing edge and increment the dependent course's indegree.","commonMistakes":["Reversing the edge direction","Incrementing indegree for the prerequisite course"],"hint":"For relation [prev, next], prev points to next, and next gains one prerequisite.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Translate every prerequisite relation into both an adjacency edge and an incoming-edge count.","doneWhen":"This step is done when each relation appends nextCourse to prevCourse's neighbor list and increments indegree[nextCourse].","shouldFailWhen":"This step should fail if graph edges and indegree counts disagree, are reversed, or only one of the two structures is populated.","roles":["prerequisite relation","adjacency edge","indegree increment"],"mustProve":["Each relation contributes one directed edge from prerequisite to dependent course.","Each relation increments the dependent course's indegree."],"mustNotAccept":["Adding edges from next to prev.","Building adjacency without updating indegree."],"equivalentVariants":["Destructure each relation into prev and next.","Use indexed access into relation pairs as long as the direction is preserved."],"proofSnippets":[{"id":"py-populate-course-graph","language":"python","code":"def minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1"}]}},{"id":"initialize-queue","title":"Queue initially available courses","description":"Push every zero-indegree course into the starting queue.","commonMistakes":["Queueing only course 1","Forgetting courses that do not appear in relations","Queueing courses with remaining prerequisites"],"hint":"The first semester can include every course whose prerequisite count is zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Seed the traversal frontier with all courses that have no prerequisites.","doneWhen":"This step is done when every course label is checked and zero-indegree courses are enqueued before semester processing starts.","shouldFailWhen":"This step should fail if the queue starts empty despite available courses or if blocked courses are queued.","roles":["zero indegree","frontier queue","first semester"],"mustProve":["Every course is considered for the initial frontier.","The enqueue condition is based on indegree being zero."],"mustNotAccept":["Starting from an arbitrary single course.","Queueing courses without checking their prerequisite counts."],"equivalentVariants":["Use a deque, queue, or list-backed FIFO frontier.","Seed the frontier from a loop over all course labels."],"proofSnippets":[{"id":"py-seed-zero-indegree-courses","language":"python","code":"from collections import deque\n\ndef minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n    queue = deque()\n    for course in range(1, n + 1):\n        if indegree[course] == 0:\n            queue.append(course)"}]}},{"id":"update-neighbors","title":"Unlock dependent courses","description":"When a course is completed, decrement each neighbor's indegree and enqueue it if all prerequisites are done.","commonMistakes":["Decrementing the completed course instead of its neighbors","Forgetting to enqueue newly zero-indegree courses","Using a strict negative check instead of equality to zero"],"hint":"Removing a completed course removes one incoming prerequisite edge from each dependent neighbor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Advance the topological frontier by decrementing neighbor indegrees and queueing newly available courses.","doneWhen":"This step is done when each popped course scans its outgoing neighbors, decrements their indegree, and enqueues neighbors whose indegree reaches zero.","shouldFailWhen":"This step should fail if neighbor indegrees are not decremented, if zero-indegree neighbors are never queued, or if the wrong adjacency direction is traversed.","roles":["completed course","dependent neighbor","frontier queue"],"mustProve":["The algorithm scans neighbors of the completed course.","Each neighbor's indegree is decremented before it can be enqueued."],"mustNotAccept":["Popping courses without updating their outgoing edges.","Queueing every neighbor without checking indegree."],"equivalentVariants":["Use a FIFO queue or deque for the frontier.","Use any loop over graph[course] that decrements indegree and enqueues at zero."],"proofSnippets":[{"id":"py-update-dependent-courses","language":"python","code":"from collections import deque\n\ndef minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n    queue = deque()\n    for course in range(1, n + 1):\n        if indegree[course] == 0:\n            queue.append(course)\n    while queue:\n        course = queue.popleft()\n        for nxt in graph[course]:\n            indegree[nxt] -= 1\n            if indegree[nxt] == 0:\n                queue.append(nxt)"}]}},{"id":"process-queue","title":"Count semesters and detect cycles","description":"Process the queue one layer at a time, count completed courses, and return -1 if some courses remain blocked.","commonMistakes":["Incrementing semesters once per course instead of once per layer","Forgetting to count completed courses","Returning semesters even when a cycle leaves courses unfinished"],"hint":"Freeze the current queue size at the start of each semester; newly unlocked courses belong to the next semester.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_topology_completion_count_decision","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Use layered topological processing to count semesters and reject cyclic prerequisite graphs.","doneWhen":"This step is done when the traversal processes one queue layer per semester, counts completed courses, and returns -1 unless all n courses were completed.","shouldFailWhen":"This step should fail if semester count is per popped course, if completion is never checked, or if cycles are treated as successful schedules.","roles":["semester layer","completed count","cycle verdict"],"mustProve":["The frontier is processed until no available courses remain.","A scalar completion count is compared with n before returning the semester count."],"mustNotAccept":["Returning a semester count without checking whether every course was processed.","Letting newly unlocked courses count in the same semester layer."],"equivalentVariants":["Use len(queue) or an equivalent frontier-size snapshot for each semester.","Use completed == n or an equivalent processed-course count to choose between semesters and -1."],"proofSnippets":[{"id":"py-process-semester-layers","language":"python","code":"from collections import deque\n\ndef minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n    queue = deque()\n    for course in range(1, n + 1):\n        if indegree[course] == 0:\n            queue.append(course)\n    semesters = 0\n    completed = 0\n    while queue:\n        level_count = len(queue)\n        for _ in range(level_count):\n            course = queue.popleft()\n            completed += 1\n            for nxt in graph[course]:\n                indegree[nxt] -= 1\n                if indegree[nxt] == 0:\n                    queue.append(nxt)\n        semesters += 1\n    return semesters if completed == n else -1"}]}}],"slides":[{"id":"read-the-signal","chapter":"The prerequisites","kind":"info","eyebrow":"Read the problem","title":"Finish every course in as few semesters as possible","workspacePanel":"problem","body":["You get n courses and a list of relations. Each relation [a, b] means a must be finished before b. In one semester you may take any number of courses at once, as long as every prerequisite of each is already done. Return the fewest semesters needed, or -1 if a loop makes it impossible.","A prerequisite cycle leaves its courses waiting on one another forever, so no semester plan exists. Otherwise, every course whose prerequisites are done can share the next semester."]},{"id":"naive-scan","chapter":"The prerequisites","kind":"code-trace","eyebrow":"The obvious way","title":"Each semester, scan every unfinished course and take the ready ones","summary":"The trace returns the right count after re-reading the whole relation list once per semester.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"done = [False] * (n + 1)\ncompleted = 0\nsemesters = 0\nwhile completed < n:\n    ready = []\n    for course in range(1, n + 1):\n        if done[course]:\n            continue\n        blocked = False\n        for prev, nxt in relations:\n            if nxt == course and not done[prev]:\n                blocked = True\n        if not blocked:\n            ready.append(course)\n    if not ready:\n        return -1\n    for course in ready:\n        done[course] = True\n        completed += 1\n    semesters += 1\nreturn semesters","steps":[{"id":"scan-sem-one","title":"Scan all unfinished courses for the first semester","codeLine":6,"summary":"n = 5, relations = [[1,4],[2,4],[3,5]]. Walk courses 1 through 5, re-reading the relation list for each to see if anything it owes is still unfinished.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"current":1}}},{"id":"take-sem-one","title":"Courses 1, 2, and 3 owe nothing, so take them","codeLine":18,"summary":"Courses 1, 2, 3 pass their scan and are taken together. Courses 4 and 5 each still fail, since they wait on courses just now finishing. One semester counted.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"current":1,"visited":[1,2,3]}}},{"id":"rescan-sem-two","title":"Start the next semester by re-scanning from scratch","codeLine":6,"summary":"completed is 3, still under 5, so loop again. Courses 4 and 5 are re-checked by re-reading every relation, even though only courses 1, 2, 3 changed.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"}],"edges":[[1,4],[2,4],[3,5]],"current":4,"visited":[1,2,3]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const done = Array((n + 1)).fill(false);\nlet completed = 0;\nlet semesters = 0;\nwhile (completed < n) {\n    const ready = [];\n    for (let course = 1; course < (n + 1); course++) {\n        if (done[course]) {\n            continue;\n        }\n        let blocked = false;\n        for (const [prev, nxt] of relations) {\n            if (nxt === course && !done[prev]) {\n                blocked = true;\n            }\n        }\n        if (!blocked) {\n            ready.push(course);\n        }\n    }\n    if (ready.length === 0) {\n        return -1;\n    }\n    for (const course of ready) {\n        done[course] = true;\n        completed++;\n    }\n    semesters++;\n}\nreturn semesters;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":16,"14":17,"15":20,"16":21,"17":23,"18":24,"19":25,"20":27,"21":29},"statementBundles":{"8":{"startLine":8,"endLine":9},"12":{"startLine":13,"endLine":15},"14":{"startLine":17,"endLine":19},"16":{"startLine":21,"endLine":22},"19":{"startLine":25,"endLine":26},"20":{"startLine":27,"endLine":28}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const done = Array((n + 1)).fill(false);\nlet completed = 0;\nlet semesters = 0;\nwhile (completed < n) {\n    const ready: Array<number> = [];\n    for (let course = 1; course < (n + 1); course++) {\n        if (done[course]) {\n            continue;\n        }\n        let blocked = false;\n        for (const [prev, nxt] of relations) {\n            if (nxt === course && !done[prev]) {\n                blocked = true;\n            }\n        }\n        if (!blocked) {\n            ready.push(course);\n        }\n    }\n    if (ready.length === 0) {\n        return -1;\n    }\n    for (const course of ready) {\n        done[course] = true;\n        completed++;\n    }\n    semesters++;\n}\nreturn semesters;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":16,"14":17,"15":20,"16":21,"17":23,"18":24,"19":25,"20":27,"21":29},"statementBundles":{"8":{"startLine":8,"endLine":9},"12":{"startLine":13,"endLine":15},"14":{"startLine":17,"endLine":19},"16":{"startLine":21,"endLine":22},"19":{"startLine":25,"endLine":26},"20":{"startLine":27,"endLine":28}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Boolean> done = new ArrayList<>();\nfor (int index = 0; index < (n + 1); index++) {\n    done.add(false);\n}\nint completed = 0;\nint semesters = 0;\nwhile (completed < n) {\n    List<Integer> ready = new ArrayList<>();\n    for (int course = 1; course < (n + 1); course++) {\n        if (done.get(course)) {\n            continue;\n        }\n        boolean blocked = false;\n        for (List<Integer> relation : relations) {\n            int prev = relation.get(0);\n            int nxt = relation.get(1);\n            if ((nxt == course && !done.get(prev))) {\n                blocked = true;\n            }\n        }\n        if (!blocked) {\n            ready.add(course);\n        }\n    }\n    if (ready.isEmpty()) {\n        return -1;\n    }\n    for (Integer course : ready) {\n        done.set(course, true);\n        completed++;\n    }\n    semesters++;\n}\nreturn semesters;","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":10,"8":11,"9":13,"10":14,"11":17,"12":18,"13":21,"14":22,"15":25,"16":26,"17":28,"18":29,"19":30,"20":32,"21":34},"statementBundles":{"1":{"startLine":1,"endLine":4},"8":{"startLine":11,"endLine":12},"10":{"startLine":14,"endLine":16},"12":{"startLine":18,"endLine":20},"14":{"startLine":22,"endLine":24},"16":{"startLine":26,"endLine":27},"19":{"startLine":30,"endLine":31},"20":{"startLine":32,"endLine":33}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<bool> done = Enumerable.Repeat<bool>(false, n + 1).ToList();\nint completed = 0;\nint semesters = 0;\nwhile (completed < n) {\n    List<int> ready = new();\n    for (int course = 1; course < n + 1; course++) {\n        if (done[course]) {\n            continue;\n        }\n        bool blocked = false;\n        foreach (var item in relations) {\n            int prev = item[0];\n            int nxt = item[1];\n            if (nxt == course && !done[prev]) {\n                blocked = true;\n            }\n        }\n        if (!blocked) {\n            ready.Add(course);\n        }\n    }\n    if (ready.Count == 0) {\n        return -1;\n    }\n    foreach (int course in ready) {\n        done[course] = true;\n        completed++;\n    }\n    semesters++;\n}\nreturn semesters;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":14,"12":15,"13":18,"14":19,"15":22,"16":23,"17":25,"18":26,"19":27,"20":29,"21":31},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":13},"12":{"startLine":15,"endLine":17},"14":{"startLine":19,"endLine":21},"16":{"startLine":23,"endLine":24},"19":{"startLine":27,"endLine":28},"20":{"startLine":29,"endLine":30}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<bool> done = vector<bool>((n + 1), false);\nint completed = 0;\nint semesters = 0;\nwhile (completed < n) {\n    vector<int> ready;\n    for (int course = 1; course < (n + 1); course++) {\n        if (done[course]) {\n            continue;\n        }\n        bool blocked = false;\n        for (vector<int> item : relations) {\n            int prev = item[0];\n            int nxt = item[1];\n            if ((nxt == course && !done[prev])) {\n                blocked = true;\n            }\n        }\n        if (!blocked) {\n            ready.push_back(course);\n        }\n    }\n    if (ready.empty()) {\n        return -1;\n    }\n    for (int course : ready) {\n        done[course] = true;\n        completed++;\n    }\n    semesters++;\n}\nreturn semesters;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":14,"12":15,"13":18,"14":19,"15":22,"16":23,"17":25,"18":26,"19":27,"20":29,"21":31},"statementBundles":{"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":13},"12":{"startLine":15,"endLine":17},"14":{"startLine":19,"endLine":21},"16":{"startLine":23,"endLine":24},"19":{"startLine":27,"endLine":28},"20":{"startLine":29,"endLine":30}}}}}},{"id":"naive-cost","chapter":"The prerequisites","kind":"case-probe","eyebrow":"Count the work","title":"How much does each semester scan cost, and how many scans run?","summary":"A semester takes a wave of ready courses, then re-reads the whole relation list to find the next wave.","workspacePanel":"trace","options":[{"id":"rescan-each-sem","label":"Each semester re-reads every relation for every unfinished course, and a long chain forces one semester per course","rationale":"A chain 1 before 2 before 3 before 4 takes exactly one course per semester, so up to n semesters run, and each one re-scans all of relations. The same prerequisites get checked over and over.","isCorrect":true},{"id":"one-scan-total","label":"One scan of the relations is enough to finish every course","rationale":"A course is usually not ready on the first scan. A chain forces a fresh scan for each course down the line, re-reading the whole list every time.","isCorrect":false},{"id":"constant-scans","label":"A fixed two or three scans always suffice","rationale":"The number of semesters grows with the longest dependency chain. A chain of n courses needs n semesters.","isCorrect":false}],"answer":"Every semester re-reads the whole relation list for each unfinished course, and a long chain forces one semester per course, so the same relations get checked again and again. The fix is to stop re-scanning and track readiness directly."},{"id":"prereqs-as-graph","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"Each prerequisite is an arrow forward","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"graph-intro","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]]}}}]},"body":["Draw an arrow from each prerequisite to the course that needs it. An arrow out of 1 into 4 means 1 must come before 4.","The number beside each course is how many prerequisites it still has waiting, the count of arrows pointing into it. Courses 1, 2, and 3 have 0; course 4 has 2; course 5 has 1."]},{"id":"state-enough","chapter":"The idea","kind":"case-probe","eyebrow":"Find the state","title":"What do you need to know to decide a course is takeable?","summary":"The naive scan re-read the whole relation list every semester. What is the smallest piece of state that decides takeability?","workspacePanel":"visualizer","options":[{"id":"waiting-count","label":"Just its count of prerequisites still waiting, the arrows pointing in","rationale":"A course is takeable exactly when that count is 0. Taking a course is then just dropping the counts of the courses it points at, with no re-scan.","isCorrect":true},{"id":"full-list","label":"The full list of which prerequisites each course has","rationale":"That is what the naive scan re-read every semester. Once you only ask whether the count is 0, the identities of the remaining prerequisites stop mattering.","isCorrect":false},{"id":"taken-order","label":"The exact order earlier courses were taken in","rationale":"Order within a semester does not affect takeability. A course comes due the moment its last prerequisite is gone, however the earlier ones were sequenced.","isCorrect":false}],"answer":"Just the waiting count. A course is takeable the instant its count reaches 0, so one number per course replaces every re-scan of the relation list.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-enough-state","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"highlighted":[1,2,3]}}}]}},{"id":"share-a-semester","chapter":"The idea","kind":"case-probe","eyebrow":"Find the waves","title":"Courses 1, 2, 3 are done. Which go in the next semester?","summary":"Courses 1, 2, and 3 were all taken in semester 1.","workspacePanel":"visualizer","options":[{"id":"four-and-five","label":"Courses 4 and 5 together, since both just reached a waiting count of 0","rationale":"Finishing 1, 2, 3 drops 4's count from 2 to 0 and 5's from 1 to 0 at the same moment, so both are takeable now and share semester 2. The answer counts semesters, so a whole batch of freed courses costs only one.","isCorrect":true},{"id":"four-then-five","label":"Course 4 in semester 2, then course 5 in semester 3","rationale":"Both 4 and 5 come due at the same time, so splitting them across semesters wastes one. A semester can hold any number of ready courses at once.","isCorrect":false},{"id":"only-four","label":"Only course 4, because it had the most prerequisites","rationale":"Course 5's last prerequisite, course 3, also just finished, so 5 is equally ready. Both take semester 2 together.","isCorrect":false}],"answer":"Courses 4 and 5 together. Both hit a waiting count of 0 the instant semester 1 ends, so they share semester 2. Counting semesters means every course freed at the same time costs just one semester between them.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"share-state","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"}],"edges":[[1,4],[2,4],[3,5]],"visited":[1,2,3],"queue":[4,5],"activeEdges":[[1,4],[2,4],[3,5]]}}}]}},{"id":"detect-cycle","chapter":"The idea","kind":"case-probe","eyebrow":"Name the failure","title":"How does taking courses in waves reveal an impossible schedule?","summary":"Here course 1 requires course 3, and course 3 requires course 1.","workspacePanel":"visualizer","options":[{"id":"count-short","label":"You run out of takeable courses before finishing them all","rationale":"Neither course ever reaches a waiting count of 0, so no semester can start and nothing is taken. Finishing fewer than every course is the signal to return -1.","isCorrect":true},{"id":"negative-count","label":"A waiting count drops below 0","rationale":"Counts only drop when a real prerequisite is finished, which never happens here, so nothing goes negative. The courses simply never come due.","isCorrect":false},{"id":"revisit","label":"You take the same course twice","rationale":"A course is taken only when its count hits 0 and is never queued again. The failure is courses never taken at all, not repeats.","isCorrect":false}],"answer":"You get stuck: no course is takeable, yet courses remain. Counting how many you actually finished and comparing to n is the cycle test. Fewer than n means a loop, so return -1.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cycle-state","state":{"graph":{"nodes":[{"id":1,"label":"1: 1"},{"id":3,"label":"3: 1"}],"edges":[[1,3],[3,1]]}}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which way should we run it?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]]}}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Take courses one wave at a time","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"queue":[1,2,3]}}}]},"body":["A queue holds every course whose waiting count is currently 0. It starts with courses 1, 2, and 3.","Each semester, take everything sitting in the queue right now, dropping the waiting count of whatever those courses point at. Any course that reaches 0 joins the queue for the next semester.","Freeze the queue size at the start of each semester so a course freed this wave waits for the next one. Count the semesters, and tally how many courses were taken to catch a cycle."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the waves","title":"Trace the schedule","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"wave-one","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"queue":[1,2,3]}}},{"id":"freed-check","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"}],"edges":[[1,4],[2,4],[3,5]],"visited":[1,2,3],"queue":[4,5]}}},{"id":"wave-two","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"}],"edges":[[1,4],[2,4],[3,5]],"visited":[1,2,3,4,5],"queue":[]}}},{"id":"result","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"},{"id":5,"label":"5: 0"}],"edges":[[1,4],[2,4],[3,5]],"visited":[1,2,3,4,5],"queue":[]}}}]},"beats":[{"id":"wave-one","title":"Semester 1 takes the whole starting queue. How many courses is that?","summary":"Courses 1, 2, and 3 are all sitting in the queue.","prompt":"The queue holds courses 1, 2, and 3, all owing nothing.","options":[{"id":"three","label":"All three: 1, 2, and 3 in one semester","rationale":"Every course in the queue right now is takeable, so all three go in semester 1. Taking them drops course 4 to 0 and course 5 to 0. Three courses done, one semester counted.","isCorrect":true},{"id":"one","label":"Just course 1, the first one","rationale":"A semester takes the entire current queue, not one course. Courses 1, 2, and 3 are all ready, so all three go at once.","isCorrect":false},{"id":"none","label":"None until course 4 is reachable","rationale":"Courses 1, 2, 3 owe nothing from the start, so they are takeable in the very first semester.","isCorrect":false}],"answer":"All three. The whole starting queue is taken in semester 1, which drops courses 4 and 5 to a waiting count of 0."},{"id":"freed-check","title":"Courses 4 and 5 both reached 0. Do they share a semester?","summary":"Both were freed by the courses just taken in semester 1.","prompt":"Course 4 lost its last prerequisite and course 5 lost its only one, in the same wave.","options":[{"id":"together","label":"Yes: both go in semester 2","rationale":"They reached 0 at the same moment, so both join the queue for the next semester and are taken together. One semester covers the whole wave.","isCorrect":true},{"id":"split","label":"No: 4 in semester 2, 5 in semester 3","rationale":"A semester holds any number of ready courses. Both 4 and 5 are ready now, so splitting them wastes a semester.","isCorrect":false},{"id":"neither","label":"Neither is ready yet","rationale":"Both counts hit 0 the instant semester 1 finished, so both are takeable in semester 2.","isCorrect":false}],"answer":"Together, in semester 2. Both hit 0 in the same wave, so the next semester takes them both."},{"id":"wave-two","title":"Semester 2 takes courses 4 and 5. What is left to do?","summary":"The second-semester queue has just been processed.","prompt":"The queue for this semester held courses 4 and 5.","options":[{"id":"nothing","label":"Nothing: all five courses are taken","rationale":"Courses 4 and 5 point at nothing further, so no new course is freed and the queue is empty. Five taken in two semesters.","isCorrect":true},{"id":"more-wave","label":"A third semester for whatever 4 and 5 unlock","rationale":"Neither 4 nor 5 has outgoing arrows, so they free no one. The schedule ends after semester 2.","isCorrect":false},{"id":"five-alone","label":"Course 5 still waits on course 4","rationale":"Course 5 was already takeable in semester 2 alongside 4; it was not waiting on it.","isCorrect":false}],"answer":"Nothing is left. Courses 4 and 5 free no one, the queue empties, and all five courses are taken."},{"id":"result","title":"After the queue drains, what does the function return?","summary":"The traversal has processed two semester layers.","prompt":"completed = 5, n = 5, and semesters = 2.","options":[{"id":"two","label":"The semester count, since every course was taken","rationale":"Each of the two waves added one to the semester count, and the tally reached all five courses, so the function returns 2.","isCorrect":true},{"id":"five","label":"The completed count of courses taken","rationale":"The answer counts semesters, not courses. Courses sharing a wave cost one semester between them, so the two waves give 2, not 5.","isCorrect":false},{"id":"minus-one","label":"-1, since the queue emptied","rationale":"An empty queue after every course is taken is success. -1 is only for a queue that empties with courses still unfinished.","isCorrect":false}],"answer":"2. Two waves each added one semester and the tally reached all five courses, so the function returns the semester count of 2."}]},{"id":"per-course-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you just add one to the count each time a course is taken?","summary":"Adding one to the semester count right where each course is taken looks like the natural spot. Watch what it does on the schedule whose real answer is 2.","workspacePanel":"trace","pitfall":"The code increments semesters inside the per-course loop, so two courses taken in the same semester count as two semesters.","whyItMatters":"The answer is a count of waves, not of courses. A whole queue of courses taken together is one semester, so the increment belongs once per wave, after draining the current queue, not once per course. Snapshot the queue length at the start of each semester and add one after the wave.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"from collections import deque\n\ndef minimumSemesters(n: int, relations: list[list[int]]) -> int:\n    graph: list[list[int]] = [[] for _ in range(n + 1)]\n    indegree: list[int] = [0] * (n + 1)\n\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n\n    queue = deque(c for c in range(1, n + 1) if indegree[c] == 0)\n    semesters = 0\n    completed = 0\n    while queue:\n        course = queue.popleft()\n        completed += 1\n        semesters += 1\n        for nxt in graph[course]:\n            indegree[nxt] -= 1\n            if indegree[nxt] == 0:\n                queue.append(nxt)\n    return semesters if completed == n else -1","steps":[{"id":"seed","title":"Courses 1 and 2 seed the queue","codeLine":11,"summary":"n = 3, relations = [[1,3],[2,3]]. Courses 1 and 2 owe nothing and start in the queue; course 3 waits on both. The real answer is 2 semesters.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 2"}],"edges":[[1,3],[2,3]],"queue":[1,2]}}},{"id":"take-one","title":"Take course 1 and bump semesters to 1","codeLine":17,"summary":"Course 1 comes off the queue, completed is 1, and semesters jumps to 1. Course 3 drops to a waiting count of 1.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 1"}],"edges":[[1,3],[2,3]],"current":1,"visited":[1],"queue":[2],"activeEdges":[[1,3]]}}},{"id":"take-two","title":"Take course 2 and bump semesters again to 2","codeLine":17,"summary":"Course 2 is taken in the same wave as 1, yet semesters is bumped to 2 anyway. Course 3 drops to 0 and joins the queue.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"}],"edges":[[1,3],[2,3]],"current":2,"visited":[1,2],"queue":[3],"activeEdges":[[2,3]]}}},{"id":"take-three","title":"Take course 3 and bump semesters to 3","codeLine":17,"summary":"Course 3 is taken, semesters becomes 3, and completed reaches 3. The code returns 3 for a schedule that really needs only 2 semesters.","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"}],"edges":[[1,3],[2,3]],"current":3,"visited":[1,2,3],"queue":[]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const graph = Array.from({ length: (n + 1) }, () => []);\nconst indegree = Array((n + 1)).fill(0);\nfor (const [prev, nxt] of relations) {\n    graph[prev].push(nxt);\n    indegree[nxt] = (indegree[nxt] + 1);\n}\nconst queue = new Deque(Array.from({ length: ((n + 1) - 1) }, (_, index) => (index + 1)).filter((c) => indegree[c] === 0));\nlet semesters = 0;\nlet completed = 0;\nwhile (queue.size() > 0) {\n    const course = queue.popFront();\n    completed++;\n    semesters++;\n    for (const nxt of graph[course]) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] === 0) {\n            queue.pushBack(nxt);\n        }\n    }\n}\nreturn (completed === n ? semesters : -1);","lineMap":{"4":1,"5":2,"7":3,"8":4,"9":5,"11":7,"12":8,"13":9,"14":10,"15":11,"16":12,"17":13,"18":14,"19":15,"20":16,"21":17,"22":21},"statementBundles":{"9":{"startLine":5,"endLine":6},"21":{"startLine":17,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const graph: Array<Array<number>> = Array.from({ length: (n + 1) }, () => []);\nconst indegree = Array((n + 1)).fill(0);\nfor (const [prev, nxt] of relations) {\n    graph[prev].push(nxt);\n    indegree[nxt] = (indegree[nxt] + 1);\n}\nconst queue: Deque<number> = new Deque(Array.from({ length: ((n + 1) - 1) }, (_, index) => (index + 1)).filter((c) => indegree[c] === 0));\nlet semesters = 0;\nlet completed = 0;\nwhile (queue.size() > 0) {\n    const course = queue.popFront()!;\n    completed++;\n    semesters++;\n    for (const nxt of graph[course]) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] === 0) {\n            queue.pushBack(nxt);\n        }\n    }\n}\nreturn (completed === n ? semesters : -1);","lineMap":{"4":1,"5":2,"7":3,"8":4,"9":5,"11":7,"12":8,"13":9,"14":10,"15":11,"16":12,"17":13,"18":14,"19":15,"20":16,"21":17,"22":21},"statementBundles":{"9":{"startLine":5,"endLine":6},"21":{"startLine":17,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<Integer>> graph = new ArrayList<>();\nfor (int i = 0; i < (n + 1); i++) {\n    graph.add(new ArrayList<>());\n}\nint[] indegree = new int[(n + 1)];\nfor (List<Integer> relation : relations) {\n    int prev = relation.get(0);\n    int nxt = relation.get(1);\n    graph.get(prev).add(nxt);\n    indegree[nxt] = (indegree[nxt] + 1);\n}\nDeque<Integer> queue = new ArrayDeque<>(java.util.stream.IntStream.range(1, (n + 1)).boxed().filter(c -> indegree[c] == 0).collect(java.util.stream.Collectors.toList()));\nint semesters = 0;\nint completed = 0;\nwhile (!queue.isEmpty()) {\n    int course = queue.pollFirst();\n    completed++;\n    semesters++;\n    for (Integer nxt : graph.get(course)) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] == 0) {\n            queue.addLast(nxt);\n        }\n    }\n}\nreturn (completed == n ? semesters : -1);","lineMap":{"4":1,"5":5,"7":6,"8":9,"9":10,"11":12,"12":13,"13":14,"14":15,"15":16,"16":17,"17":18,"18":19,"19":20,"20":21,"21":22,"22":26},"statementBundles":{"4":{"startLine":1,"endLine":4},"7":{"startLine":6,"endLine":8},"9":{"startLine":10,"endLine":11},"21":{"startLine":22,"endLine":25}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> graph = Enumerable.Range(0, n + 1).Select(_ => new List<int>()).ToList();\nList<int> indegree = Enumerable.Repeat<int>(0, n + 1).ToList();\nforeach (var item in relations) {\n    int prev = item[0];\n    int nxt = item[1];\n    graph[prev].Add(nxt);\n    indegree[nxt] = indegree[nxt] + 1;\n}\nQueue<int> queue = new(Enumerable.Range(1, n + 1 - 1).Where(c => indegree[c] == 0).Select(c => c).ToList());\nint semesters = 0;\nint completed = 0;\nwhile (queue.Count > 0) {\n    int course = queue.Dequeue();\n    completed++;\n    semesters++;\n    foreach (int nxt in graph[course]) {\n        indegree[nxt] = indegree[nxt] - 1;\n        if (indegree[nxt] == 0) {\n            queue.Enqueue(nxt);\n        }\n    }\n}\nreturn (completed == n ? semesters : -1);","lineMap":{"4":1,"5":2,"7":3,"8":6,"9":7,"11":9,"12":10,"13":11,"14":12,"15":13,"16":14,"17":15,"18":16,"19":17,"20":18,"21":19,"22":23},"statementBundles":{"7":{"startLine":3,"endLine":5},"9":{"startLine":7,"endLine":8},"21":{"startLine":19,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<int>> graph = vector<vector<int>>((n + 1), vector<int>{});\nvector<int> indegree = vector<int>((n + 1), 0);\nfor (vector<int> item : relations) {\n    int prev = item[0];\n    int nxt = item[1];\n    graph[prev].push_back(nxt);\n    indegree[nxt] = (indegree[nxt] + 1);\n}\ndeque<int> queue;\nfor (int c = 1; c < (n + 1); c++) {\n    if (indegree[c] == 0) {\n        queue.push_back(c);\n    }\n}\nint semesters = 0;\nint completed = 0;\nwhile (!queue.empty()) {\n    int course = queue.front();\n    queue.pop_front();\n    completed++;\n    semesters++;\n    for (int nxt : graph[course]) {\n        indegree[nxt] = (indegree[nxt] - 1);\n        if (indegree[nxt] == 0) {\n            queue.push_back(nxt);\n        }\n    }\n}\nreturn (completed == n ? semesters : -1);","lineMap":{"4":1,"5":2,"7":3,"8":6,"9":7,"11":9,"12":15,"13":16,"14":17,"15":18,"16":20,"17":21,"18":22,"19":23,"20":24,"21":25,"22":29},"statementBundles":{"7":{"startLine":3,"endLine":5},"9":{"startLine":7,"endLine":8},"11":{"startLine":9,"endLine":14},"15":{"startLine":18,"endLine":19},"21":{"startLine":25,"endLine":28}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Taking courses in waves cleared the sample schedule in two semesters, each wave coming off the queue until the tally matched n.","Two thin schedules are worth poking at before you code: one where no course has any prerequisite, and one where two courses each require the other."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"queue":[1,2,3]}}}]}},{"id":"no-relations-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if no course has any prerequisite?","summary":"4 courses, no relations at all.","workspacePanel":"visualizer","options":[{"id":"one-sem","label":"Every course is takeable at once, so the answer is 1","rationale":"With no arrows, every waiting count is 0, so the queue starts with all four. They all go in a single wave, and one semester finishes them.","isCorrect":true},{"id":"four-sem","label":"Four semesters, one course each","rationale":"A semester holds any number of ready courses. All four are ready from the start, so they share one semester, not four.","isCorrect":false},{"id":"zero-sem","label":"0, since there is nothing blocking","rationale":"There are still courses to take, and taking a non-empty wave costs one semester. The answer is 1, not 0.","isCorrect":false}],"answer":"1. With no relations every course starts at a waiting count of 0, so the whole set is taken in a single wave and one semester finishes them all.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-relations-state","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 0"}],"edges":[],"queue":[1,2,3,4]}}}]}},{"id":"cycle-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if three courses form a loop?","summary":"Course 1 needs 3, course 2 needs 1, course 3 needs 2.","workspacePanel":"visualizer","options":[{"id":"minus-one","label":"-1: the schedule is impossible","rationale":"Every course in the loop waits on another, so none ever reaches a waiting count of 0. The queue starts empty, nothing is taken, and the tally stays below n, which returns -1.","isCorrect":true},{"id":"three","label":"3, one course per semester","rationale":"No course can go first, so no semester ever starts. A loop is not a chain; the answer is -1, not 3.","isCorrect":false},{"id":"two","label":"2, breaking the loop somewhere","rationale":"There is no place to break it: each of the three waits on another forever. Nothing is takeable, so the answer is -1.","isCorrect":false}],"answer":"-1. Each course waits on another in the loop, so the queue never starts, the tally stays below n, and the count check reports the schedule as impossible.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cycle-edge-state","state":{"graph":{"nodes":[{"id":1,"label":"1: 1"},{"id":2,"label":"2: 1"},{"id":3,"label":"3: 1"}],"edges":[[1,2],[2,3],[3,1]]}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Take courses in waves, then count the waves","summary":"The move that makes it work: take the whole current queue as one semester, and only after draining it add one to the semester count.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"graph":{"nodes":[{"id":1,"label":"1: 0"},{"id":2,"label":"2: 0"},{"id":3,"label":"3: 0"},{"id":4,"label":"4: 2"},{"id":5,"label":"5: 1"}],"edges":[[1,4],[2,4],[3,5]],"queue":[1,2,3]}}}]},"body":["Count each course's remaining prerequisites and note which courses depend on it, then queue everything that starts at zero. Each semester, take every course sitting in the queue right now, ease their dependents, and queue any that reach zero. Add one to the semester count per wave, and at the end check whether the number taken equals n, returning -1 if it falls short."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the course-wave scheduler","eyebrow":"Build the solution","summary":"Build the adjacency lists and indegree counts, seed the queue with zero-indegree courses, then process one wave per semester and check that every course was taken.","workspacePanel":"code","checkpoints":[{"id":"build-graph","title":"Create adjacency lists","description":"Allocate an adjacency list for every course label.","commonMistakes":["Allocating only n slots for 1-indexed courses","Using one shared list for every course"],"hint":"Use n + 1 slots so course labels can be used directly as indexes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_adjacency","scope":"build-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Create a directed adjacency structure that can store outgoing unlocked-course edges.","doneWhen":"This step is done when every course label has a bucket for outgoing neighbors before relations are scanned.","shouldFailWhen":"This step should fail if no adjacency state exists or if all courses accidentally share the same neighbor list.","roles":["course graph","outgoing edges","course label"],"mustProve":["The graph state is initialized before prerequisite relations are processed.","The graph has enough slots or keys for every course label."],"mustNotAccept":["Trying to derive neighbors by rescanning relations later.","Using a scalar where adjacency lists are required."],"equivalentVariants":["Use a list of lists indexed by course label.","Use a map from course to a fresh neighbor list."],"proofSnippets":[{"id":"py-create-course-adjacency","language":"python","code":"def minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]"}]}},{"id":"calculate-indegree","title":"Create indegree counts","description":"Allocate an indegree count for every course.","commonMistakes":["Counting outgoing edges instead of incoming prerequisites","Forgetting isolated courses"],"hint":"Indegree stores how many prerequisites still block each course.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Create the counter state used to decide when a course becomes available.","doneWhen":"This step is done when every course has an initial zero prerequisite count before relations are scanned.","shouldFailWhen":"This step should fail if the solution has no counter state or initializes counts only for courses that appear as destinations.","roles":["indegree","prerequisite count","course label"],"mustProve":["The indegree state is initialized for the course domain.","The counts start at zero before relation population."],"mustNotAccept":["Using the adjacency list length as a substitute for incoming prerequisite count.","Skipping courses with no relation entries."],"equivalentVariants":["Use a zero-filled array of length n + 1.","Use a map with zero default values for course labels."],"proofSnippets":[{"id":"py-create-course-indegree","language":"python","code":"def minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)"}]}},{"id":"populate-graph","title":"Populate graph and indegree","description":"For each prerequisite pair, add the outgoing edge and increment the dependent course's indegree.","commonMistakes":["Reversing the edge direction","Incrementing indegree for the prerequisite course"],"hint":"For relation [prev, next], prev points to next, and next gains one prerequisite.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Translate every prerequisite relation into both an adjacency edge and an incoming-edge count.","doneWhen":"This step is done when each relation appends nextCourse to prevCourse's neighbor list and increments indegree[nextCourse].","shouldFailWhen":"This step should fail if graph edges and indegree counts disagree, are reversed, or only one of the two structures is populated.","roles":["prerequisite relation","adjacency edge","indegree increment"],"mustProve":["Each relation contributes one directed edge from prerequisite to dependent course.","Each relation increments the dependent course's indegree."],"mustNotAccept":["Adding edges from next to prev.","Building adjacency without updating indegree."],"equivalentVariants":["Destructure each relation into prev and next.","Use indexed access into relation pairs as long as the direction is preserved."],"proofSnippets":[{"id":"py-populate-course-graph","language":"python","code":"def minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1"}]}},{"id":"initialize-queue","title":"Queue initially available courses","description":"Push every zero-indegree course into the starting queue.","commonMistakes":["Queueing only course 1","Forgetting courses that do not appear in relations","Queueing courses with remaining prerequisites"],"hint":"The first semester can include every course whose prerequisite count is zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Seed the traversal frontier with all courses that have no prerequisites.","doneWhen":"This step is done when every course label is checked and zero-indegree courses are enqueued before semester processing starts.","shouldFailWhen":"This step should fail if the queue starts empty despite available courses or if blocked courses are queued.","roles":["zero indegree","frontier queue","first semester"],"mustProve":["Every course is considered for the initial frontier.","The enqueue condition is based on indegree being zero."],"mustNotAccept":["Starting from an arbitrary single course.","Queueing courses without checking their prerequisite counts."],"equivalentVariants":["Use a deque, queue, or list-backed FIFO frontier.","Seed the frontier from a loop over all course labels."],"proofSnippets":[{"id":"py-seed-zero-indegree-courses","language":"python","code":"from collections import deque\n\ndef minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n    queue = deque()\n    for course in range(1, n + 1):\n        if indegree[course] == 0:\n            queue.append(course)"}]}},{"id":"update-neighbors","title":"Unlock dependent courses","description":"When a course is completed, decrement each neighbor's indegree and enqueue it if all prerequisites are done.","commonMistakes":["Decrementing the completed course instead of its neighbors","Forgetting to enqueue newly zero-indegree courses","Using a strict negative check instead of equality to zero"],"hint":"Removing a completed course removes one incoming prerequisite edge from each dependent neighbor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Advance the topological frontier by decrementing neighbor indegrees and queueing newly available courses.","doneWhen":"This step is done when each popped course scans its outgoing neighbors, decrements their indegree, and enqueues neighbors whose indegree reaches zero.","shouldFailWhen":"This step should fail if neighbor indegrees are not decremented, if zero-indegree neighbors are never queued, or if the wrong adjacency direction is traversed.","roles":["completed course","dependent neighbor","frontier queue"],"mustProve":["The algorithm scans neighbors of the completed course.","Each neighbor's indegree is decremented before it can be enqueued."],"mustNotAccept":["Popping courses without updating their outgoing edges.","Queueing every neighbor without checking indegree."],"equivalentVariants":["Use a FIFO queue or deque for the frontier.","Use any loop over graph[course] that decrements indegree and enqueues at zero."],"proofSnippets":[{"id":"py-update-dependent-courses","language":"python","code":"from collections import deque\n\ndef minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n    queue = deque()\n    for course in range(1, n + 1):\n        if indegree[course] == 0:\n            queue.append(course)\n    while queue:\n        course = queue.popleft()\n        for nxt in graph[course]:\n            indegree[nxt] -= 1\n            if indegree[nxt] == 0:\n                queue.append(nxt)"}]}},{"id":"process-queue","title":"Count semesters and detect cycles","description":"Process the queue one layer at a time, count completed courses, and return -1 if some courses remain blocked.","commonMistakes":["Incrementing semesters once per course instead of once per layer","Forgetting to count completed courses","Returning semesters even when a cycle leaves courses unfinished"],"hint":"Freeze the current queue size at the start of each semester; newly unlocked courses belong to the next semester.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_topology_completion_count_decision","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Use layered topological processing to count semesters and reject cyclic prerequisite graphs.","doneWhen":"This step is done when the traversal processes one queue layer per semester, counts completed courses, and returns -1 unless all n courses were completed.","shouldFailWhen":"This step should fail if semester count is per popped course, if completion is never checked, or if cycles are treated as successful schedules.","roles":["semester layer","completed count","cycle verdict"],"mustProve":["The frontier is processed until no available courses remain.","A scalar completion count is compared with n before returning the semester count."],"mustNotAccept":["Returning a semester count without checking whether every course was processed.","Letting newly unlocked courses count in the same semester layer."],"equivalentVariants":["Use len(queue) or an equivalent frontier-size snapshot for each semester.","Use completed == n or an equivalent processed-course count to choose between semesters and -1."],"proofSnippets":[{"id":"py-process-semester-layers","language":"python","code":"from collections import deque\n\ndef minimumSemesters(n, relations):\n    graph = [[] for _ in range(n + 1)]\n    indegree = [0] * (n + 1)\n    for prev, nxt in relations:\n        graph[prev].append(nxt)\n        indegree[nxt] += 1\n    queue = deque()\n    for course in range(1, n + 1):\n        if indegree[course] == 0:\n            queue.append(course)\n    semesters = 0\n    completed = 0\n    while queue:\n        level_count = len(queue)\n        for _ in range(level_count):\n            course = queue.popleft()\n            completed += 1\n            for nxt in graph[course]:\n                indegree[nxt] -= 1\n                if indegree[nxt] == 0:\n                    queue.append(nxt)\n        semesters += 1\n    return semesters if completed == n else -1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Take every course with no remaining prerequisites at once; the number of waves is the answer, and a cycle is what traps the rest.","workspacePanel":"code","body":["Model courses as a graph and process the ready courses one wave at a time: take everything currently at a waiting count of zero together, free the courses that depend on them, and queue any that just reached zero.","Count one semester per wave, not per course, and tally how many courses you took. Take all n and the wave count is the answer; if some never reach zero, a cycle blocks them and the answer is -1."],"takeaways":[{"title":"A wave is one semester","body":"Every course at a waiting count of zero at the same moment can be taken together, so processing the queue one frozen layer at a time and counting layers gives the minimum semesters."},{"title":"Count layers, not courses","body":"Snapshotting the queue size at the start of each semester is what separates this from plain topological order: the increment lands once per wave, after the wave drains."},{"title":"An unfinished tally is a cycle","body":"Courses left untaken after the queue empties are exactly those caught in a loop, so comparing the taken count to n decides between an answer and -1."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
